ByteBuddy 如何创建一个class 并在class 中调用另一个构造函数的构造函数?

ByteBuddy how to create a class with constructor calling another constructor in the class?

我正在尝试使用 ByteBuddy 动态创建这样的 class:

Class A{

  public A(){
    this(1); 
  }

  public A(int n){
    ...
  }
}

有人知道我如何使用 bytebuddy 做到这一点吗?

应该很简单:

new ByteBuddy()
  .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
  .defineConstructor(Visibility.PUBLIC)
  .withParameters(int.class)
  .intercept(MethodCall.invoke(Object.class.getConstructor()))
  .defineConstructor(Visibility.PUBLIC)
  .intercept(MethodCall.invoke(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(int.class))).with(1))
  .make()
  .load(null)
  .getLoaded();

不幸的是,目前 Byte Buddy 中存在一个错误,该错误会阻止使用此 API 匹配自声明的构造函数。此错误已修复,将与 Byte Buddy 1.11.1 一起发布。