字节好友 - 定义构造函数,用呼叫超级类和初始化字段



我有一个类,例如:

public class Sample{
private String a;
private String b;
public Sample(String a, String b)
{
    this.a = a;
    this.b = b;
}
 public String getA() {return a;}
 public String getB() {return b;}
}

我想创建一个动态类,该类将从示例类继承,然后在其中添加字段(字符串字段)。

我试图做:

DynamicType.Builder<? extends Sample> classBuilder = new ByteBuddy()
        .subclass(Sample.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
        .name("sampleSon");
classBuilder.defineConstructor(Visibility.PUBLIC)
        .withParameters(String.class, String.class, String.class)
        .intercept(MethodCall.invoke(Sample.class.getConstructor(String.class, String.class))
                .withArgument(0, 1)
                .andThen(FieldAccessor.ofField("c").setsArgumentAt(2)));

但是,当我尝试从此类创建一个实例时:

Class<? extends Sample> newSampleClass= classBuilder.make().load(ClassLoader.getSystemClassLoader()).getLoaded();
Sample sample = newSampleClass.getConstructor(String.class, String.class, String.class).newInstance("a", "b", "c");

它引发了例外:

java.lang.NoSuchMethodException: sampleSon.<init>(java.lang.String, java.lang.String, java.lang.String)

我在做什么错?我想创建一个这样的课程:

public class SampleSon extends Sample {
     private String c;
     public SampleSon(String a, String b, String c) {
       super(a,b);
       this.c = c;
     }
     public String getC() { return c;}
}

在开始在构造函数定义中使用它之前,您不定义字段c

Class<? extends Sample> clazz = new ByteBuddy()
        .subclass(Sample.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
        .name("SampleSon")
        .defineField("c", String.class, Visibility.PRIVATE)
        .defineConstructor(Visibility.PUBLIC)
        .withParameters(String.class, String.class, String.class)
        .intercept(MethodCall.invoke(Sample.class.getConstructor(String.class, String.class))
                .withArgument(0, 1)
                .andThen(FieldAccessor.ofField("c").setsArgumentAt(2)))
        .make()
        .load(ClassLoader.getSystemClassLoader())
        .getLoaded();

注意:您还需要根据ByteBuddy的Javadoc链接所有方法。

相关内容

  • 没有找到相关文章

最新更新