Adding a field to Java class

2019-07-03 23:21发布

问题:

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.