Reputation: 986
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?
Upvotes: 1
Views: 282
Reputation: 986
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))
);
Upvotes: 1
Reputation: 44032
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.
Upvotes: 1