Search code examples
javaproxybytecodejavassistcglib

Which library to choose for generating classes at runtime


I need to extend classes at runtime, particularly to detect changes made to classes state. If it's possible I would like to be able to detect changes by intercepting field assignments, if not intercepting setters would be ok. Which library should I use and why ? javassist or cglib or ? Is this possible with java.lang.reflect.Proxy ? Can you compare these libraries ? Thanks.


Solution

  • To intercept setters defined in an interface, you can use a Proxy.

    To intercept method calls you can use an AOP like AspectJ.

    However, to trap field assignments, I would use a byte code library like ASM, BCEL, cglib or javassist. I prefer ASM and it is fast and has some tools to make writing the byte code easier.