javabyte-buddy

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?


Solution

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