简体   繁体   中英

ByteBuddy invoke constructor in same class with argument transformation

I have a Java class similar to this:

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:

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

I have tried with Advice and MethodDelegation but without success. What is the right way to achieve this with 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.

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.

Thanks for the suggested approach Rafael Winterhalter, I achieved what I wanted with the following:

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))
                    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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