I am trying to dynamically create a class using ByteBuddy with my custom constructor. I have read the Intercepting default constructor with Byte Buddy and I have written the following code base on that.
Class<?> dynamicType = new ByteBuddy().subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
.name("foo").defineConstructor(Modifier.PUBLIC).withParameters(int.class)
.intercept(
to(new Object() {
public void construct() throws Exception {
System.out.println("before constructor");
}
})
.andThen(MethodCall.invoke(Object.class.getConstructor()))
.andThen(to(new Object() {
public void construct() throws Exception {
System.out.println("after constructor");
}})
))
.make()
.load(Main.class.getClassLoader(), INJECTION)
.getLoaded();
dynamicType.getConstructor(int.class).newInstance(3);
My question is how can I access the integer argument of 'foo' constructor in the custom codes that I have added before and after calling the super constructor.
Sure, simply define a parameter with an annotation @Argument(0).
I'd recommend against using anonymous classes as their package-private visibility might render tricky outcomes.