Search code examples
javaproxycglib

Add default constructor in a java class in runtime


I'm writing a lib and I need to create proxies for some objects. Since some classes don't implement any interfaces then I decided to use CGLIB to create proxies instead of JDK proxy. But I faced with situation when some classes don't have default constructor and CGLIB fails to create proxies for those types, i.e. CGLIB throws exception with message: Superclass has no null constructors but no arguments were given. How I can solve this problem, is there some way to add default constructor in runtime using cglib/asm or some another instrument? Thanks.


Solution

  • Use http://objenesis.org/. One of its typical use cases exactly addresses your problem:

    Proxies, AOP Libraries and Mock Objects - Classes can be subclassed without needing to worry about the super() constructor.