Extending or adding new classes at runtime in Java

巧了我就是萌 提交于 2019-11-28 04:28:13

问题


Is there a way to add (or extend existing) classes at runtime in java. I'm stuck on a problem, in which I have to extend an existing class at runtime and add this to the classpath, so that this new class get picked up.

thanks,


回答1:


There are a number of ways you could do this.

  • Compile source code at runtime using the javax.tools package and then load them using a ClassLoader.
  • If you are writing to interfaces, you can decorate classes with a Proxy.
  • Take the more complicated route of bytecode manipulation/generation using a technology like BCEL or ASM (the latter has more up-to-date support for language features, like annotations) and then load the class with a ClassLoader.

I imagine there are other options.




回答2:


You might want to look at BCEL. Without any more information about what you need to do, it's tricky to give a more specific answer.




回答3:


You should definitely write why you need this feature. If you attempt to add or replace logic at runtime you might want to have a look at the scripting API and some actual implementations.



来源:https://stackoverflow.com/questions/1011443/extending-or-adding-new-classes-at-runtime-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!