简体   繁体   English

ByteBuddy 使用参数转换在同一类中调用构造函数

[英]ByteBuddy invoke constructor in same class with argument transformation

I have a Java class similar to this:我有一个类似的Java类:

public class A {

    public A(int a) {
        // ...
    }

    public A(String a) {
        // ...
    }

}

Given that I cannot edit the class or create a sub-class of it, I would like to achieve with byte-buddy the following:鉴于我无法编辑该类或创建它的子类,我想使用 byte-buddy 实现以下目标:

public A(int a) {
    this(Integer.toString(a));
}

I have tried with Advice and MethodDelegation but without success.我尝试过 Advice 和 MethodDelegation 但没有成功。 What is the right way to achieve this with byte-buddy?使用 byte-buddy 实现这一目标的正确方法是什么?

Constructors are special in the way that they do not allow the super constructor to be invoked from the outside.构造函数的特殊之处在于它们不允许从外部调用超级构造函数。 If you redefine the method, you can however use MethodCall to define such a constructor.如果重新定义方法,则可以使用 MethodCall 来定义这样的构造函数。

you'd need to define a method call to the super constructor which accepts a method call to the toString method on the only argument.您需要定义对超级构造函数的方法调用,该构造函数接受对唯一参数的 toString 方法的方法调用。

Thanks for the suggested approach Rafael Winterhalter, I achieved what I wanted with the following:感谢 Rafael Winterhalter 的建议方法,我通过以下方式实现了我想要的:

new ByteBuddy().redefine(A.class)
                    .constructor(isConstructor().and(takesArgument(0, int.class)))
                    .intercept(invoke(isConstructor().and(takesArguments(String.class)))
                            .withMethodCall(invoke(Integer.class.getMethod("toString", int.class)).withArgument(0))
                    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM