简体   繁体   中英

Create a dynamic proxy for a class without no-argument constructor

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 (eg 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)?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM