[英]How to create a default constructor with ByteBuddy?
I use ByteBuddy and I have this code:我使用 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;
}
}
My current generation code is:我当前的生成代码是:
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();
I want to get instance of class A
, and also I want to make some actions in constructor after invoke super()
, like this:我想获得
A
类A
实例,并且我想在调用super()
之后在构造函数中进行一些操作,如下所示:
public A(){
super("message");
// do something special..
}
I tried implement with MethodDelegation.to(DefaultConstructorInterceptor.class)
, but I didn't succeed.我尝试使用
MethodDelegation.to(DefaultConstructorInterceptor.class)
,但没有成功。
The JVM requires you to hard-code the super method call into a method what is not possible using delegation (also see the javadoc), this is why you cannot use the MethodDelegation
to invoke the constructor. JVM 要求您将超级方法调用硬编码为使用委托无法实现的方法(另请参阅 javadoc),这就是您不能使用
MethodDelegation
来调用构造函数的原因。 What you can do is to chain the method call you already have and the delegation by using composition by the andThen
step as in:您可以做的是通过使用
andThen
步骤的组合来链接您已经拥有的方法调用和委托,如下所示:
MethodCall.invoke(declaredConstructor).with("message")
.andThen(MethodDelegation.to(DefaultConstructorInterceptor.class));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.