gpt4 book ai didi

java - 如果代理类具有包私有(private)默认构造函数,则代理实例化失败

转载 作者:行者123 更新时间:2023-11-30 08:40:48 25 4
gpt4 key购买 nike

我想使用 ByteBuddy 为具有包私有(private)默认构造函数的类型创建代理。就是这种类型:

public class Foo {

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.WRAPPER)
.getLoaded();

Foo foo = proxyType.newInstance();
}
}

所以我试图将公共(public)默认构造函数添加到我的代理类型,拦截它的调用并委托(delegate)给父类(super class)型构造函数。尽管在生成的构造函数中出现 IllegalAccessException 失败了:

Exception in thread "main" java.lang.IllegalAccessError:
tried to access method com.example.proxy.test.Foo.&lt;init&gt;()V from class com.example.proxy.test.Foo$ByteBuddy$65mxf95M
com.example.proxy.test.Foo$ByteBuddy$65mxf95M.&lt;init&gt;(Unknown Source)
...
at java.lang.Class.newInstance(Class.java:442)
at com.example.proxy.test.CreateAndExecuteProxy.main(CreateAndExecuteProxy.java:33)

由于代理与被代理类在同一个包中,我不清楚调用失败的原因。我在这里做错了什么?是否有另一种方法可以让代理调用具有默认可见性的 super 构造函数?

最佳答案

类被两个不同的类加载器加载。请将您的策略​​更改为 INJECTION 并尝试。

ClassLoadingStrategy.Default.INJECTION

关于java - 如果代理类具有包私有(private)默认构造函数,则代理实例化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35455952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com