
[英]How to create dynamic proxy of class with no public constructor using ByteBuddy
[英]How to create a default constructor with ByteBuddy?
我使用 ByteBuddy 并且有以下代码:
public class A extends B {
public A(String a) {
super(a);
}
public String getValue() {
return "HARDCODED VALUE";
}
}
public abstract class B {
private final String message;
protected B(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
我当前的生成代码是:
Constructor<T> declaredConstructor;
try {
declaredConstructor = A.class.getDeclaredConstructor(String.class);
} catch (NoSuchMethodException e) {
//fail with exception..
}
new ByteBuddy()
.subclass(A.class, Default.IMITATE_SUPER_CLASS)
.name(A.class.getCanonicalName() + "$Generated")
.defineConstructor(Visibility.PUBLIC)
.intercept(MethodCall.invoke(declaredConstructor).with("message"))
.make()
.load(tClass.getClassLoader(),ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.newInstance();
我想获得A
类A
实例,并且我想在调用super()
之后在构造函数中进行一些操作,如下所示:
public A(){
super("message");
// do something special..
}
我尝试使用MethodDelegation.to(DefaultConstructorInterceptor.class)
,但没有成功。
JVM 要求您将超级方法调用硬编码为使用委托无法实现的方法(另请参阅 javadoc),这就是您不能使用MethodDelegation
来调用构造函数的原因。 您可以做的是通过使用andThen
步骤的组合来链接您已经拥有的方法调用和委托,如下所示:
MethodCall.invoke(declaredConstructor).with("message")
.andThen(MethodDelegation.to(DefaultConstructorInterceptor.class));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.