Adding a field to Java class

只愿长相守 提交于 2019-12-23 19:19:07

问题


Looked at using CGLib, ASM, BCEL (aspect) and Javassist to add a field to a class during runtime....

Just to get my head straight it looks like these bytecode manipulators don't update the actual class rather allow the user to only dump the modification (like with CGLib and the writeFile method). Was hoping I would find a solution that (a) loaded the class (rather than doing an InputStream with BCEL) and (b) updated the class.

Maybe this is normal? Do people usually create a proxy and pass the proxy around?

What I want to do is to add a field (note: not a property via get/set methods) before passing the object along to a framework that looks for fields (not properties) with a particular annotation. So "clients" are creating my target classes that I want to inject with an extra field. Intercepting with AOP calls to a service layer where I want to manipulate these objects.


回答1:


You can redefine classes with Intrumentation. However a common limiation is that you cannot change the fields used. This is because you cannot change the contents of a object (or add to it) once it has been created.

In your case you can,

  • create a proxy as you suggest, however proxies need to be interfaces.
  • create a subclass which has the additional field(s)
  • add the field before the class has loaded.


来源:https://stackoverflow.com/questions/11828160/adding-a-field-to-java-class

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