[英]How can I create a proxy when the class having only one private constructor?
我想使用ByteBuddy为具有私有构造函数的类创建代理。 那是课程:
public class Foo {
private Foo() {
}
}
我试过写一些这样的代码,但是行不通?
public class CreateAndExecuteProxy {
public static void main(String[] args) throws Exception {
Constructor<?> superConstructor = Foo.class.getDeclaredConstructor();
Class<? extends Foo> proxyType = new ByteBuddy()
.subclass( Foo.class, ConstructorStrategy.Default.NO_CONSTRUCTORS )
.defineConstructor( Visibility.PUBLIC )
.intercept( MethodCall.invoke( superConstructor ).onSuper() )
.make()
.load( CreateAndExecuteProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
Foo foo = proxyType.newInstance();
}
}
不允许调用私有构造函数的Java字节码真的无法做任何事情。 您有两种选择:
ByteBuddy::redefine
添加另一个构造函数,并使用代理或过早加载将此类强制装入类加载器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.