Reputation: 83
I am trying to dynamically create a class like this with ByteBuddy:
Class A{
public A(){
this(1);
}
public A(int n){
...
}
}
does any body know how can I do this using bytebuddy ?
Upvotes: 0
Views: 515
Reputation: 43972
It should be as easy as:
new ByteBuddy()
.subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
.defineConstructor(Visibility.PUBLIC)
.withParameters(int.class)
.intercept(MethodCall.invoke(Object.class.getConstructor()))
.defineConstructor(Visibility.PUBLIC)
.intercept(MethodCall.invoke(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(int.class))).with(1))
.make()
.load(null)
.getLoaded();
Unfortunately, there is currently a bug in Byte Buddy that prevents matching self-declared constructors using this API. This error is already fixed and will be released with Byte Buddy 1.11.1.
Upvotes: 2