[英]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. 有一些答案描述了为此目的使用cglib或Javassist的情况(例如https://stackoverflow.com/a/4449998/ ),但是我遇到了麻烦,因为我对代理感兴趣的类没有无参数构造函数,因此
Enhancer.create()
引发异常。 Looking at Javassist ProxyFactory
javadoc, it needs constructor arguments as well. 查看Javassist
ProxyFactory
javadoc,它也需要构造函数参数。
The obvious workaround is finding constructor argument types by reflection and passing an array of nulls/0/etc. 显而易见的解决方法是通过反射查找构造函数参数类型并传递null / 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. 您可以使用Objenesis ,它被实现为几个JVM特定类的包装。 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.
但是,使用Objenesis可能不安全,因为特定于JVM的类不是可移植的或标准化的。 For this reason, libraries like Spring or Hibernate rather require a no-argument constructor.
因此,像Spring或Hibernate之类的库都需要一个无参数的构造函数。
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 . 无耻插件:如果您通常在寻找仍在积极开发的javassist / cglib的替代产品,请查看我的库bytebuddy.net 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.