Java 如何使用ByteBuddy创建默认构造函数?
我使用ByteBuddy,我有以下代码:Java 如何使用ByteBuddy创建默认构造函数?,java,code-generation,bytecode,byte-buddy,Java,Code Generation,Bytecode,Byte Buddy,我使用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(S
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();
我尝试使用
MethodDelegation.to(DefaultConstructorInterceptor.class)
实现,但没有成功。JVM要求您将超级方法调用硬编码到方法中,这是使用委派无法实现的(也请参见javadoc),这就是为什么您不能使用MethodDelegation
调用构造函数。您可以做的是通过使用的组合来链接您已经拥有的方法调用和委托,然后执行步骤,如中所示:
MethodCall.invoke(declaredConstructor).with("message")
.andThen(MethodDelegation.to(DefaultConstructorInterceptor.class));
MethodCall.invoke(declaredConstructor).with("message")
.andThen(MethodDelegation.to(DefaultConstructorInterceptor.class));