1

I want to create a proxy for a class instead of an interface. There are answers describing use of cglib or Javassist for this purpose (e.g. https://stackoverflow.com/a/4449998/), but I've run into a wrinkle, as the class I am interested in proxying doesn't have a no-argument constructor, so Enhancer.create() throws an exception. Looking at Javassist ProxyFactory javadoc, it needs constructor arguments as well.

The obvious workaround is finding constructor argument types by reflection and passing an array of nulls/0/etc. but this won't work if the constructor throws an exception.

Are there better alternatives (perhaps using some other library)?

1 Answer 1

5

You could use Objenesis which is implemented as a wrapper around several JVM specific classes. As a result, this library allows you to create an instance of a class without calling any of its constructors. However, using Objenesis is potentially unsafe since the JVM-specific classes are not portable or standardized. For this reason, libraries like Spring or Hibernate rather require a no-argument constructor.

Shameless plug: If you in generally looking for an alternative to javassist / cglib that is still actively developed, have a look at my library bytebuddy.net.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, so I create a proxy class with cglib/javassist/ByteBuddy and then create its instance with Objenesis?
Yes. That's what you do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.