简体   繁体   English

为无参数构造函数的类创建动态代理

[英]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.

相关问题 Scala类的最终def this()声明没有公共的无参数构造函数 - Scala class final def this() declares no public no-argument constructor 无参构造函数调用2参数构造函数 - No-argument constructor calling 2-argument constructor 即使子类已经有一个已定义的构造函数,父类是否总是需要一个默认或无参数的构造函数? - Does a parent class always need a default or no-argument constructor even if the child class already has a defined constructor? Exception或其子类中的无参数构造函数 - No-argument constructor in Exception or its subclasses 隐式调用超类中的无参数构造函数 - Calling no-argument constructor in superclass implicitly 强制超类包含无参数构造函数 - Force superclasses to include a no-argument constructor cglib:不带构造函数的类的Java动态代理(HttpUrlConnection) - cglib: Java dynamic proxy for class without constructor (HttpUrlConnection) 如何使用ByteBuddy创建没有公共构造函数的类的动态代理 - How to create dynamic proxy of class with no public constructor using ByteBuddy 在编译时强制存在无参数构造函数(Java) - Enforce presence of no-argument constructor at compile time (Java) Firebase数据库:尽管存在错误,但仍出现“无参数构造函数”错误 - Firebase Database: Getting “No-Argument Constructor” Error Despite Having It
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM