I need to create a class with updated private field.
This is my code:
public class ByteBuddyTest {
public static class Foo {
}
public static class Bar {
private Foo foo;
public Foo getFoo() {
return foo;
}
}
public static void main(String[] args) throws Exception{
Class<? extends Bar> clazz = new ByteBuddy()
.subclass(Bar.class)
.??? //LINE X
.make()
.load(ByteBuddyTest.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
var bar1 = clazz
.getDeclaredConstructor()
.newInstance();
System.out.println(bar1.getFoo());
}
}
At line X
I need to set a new instance of Foo
to field Bar.foo
for every instance of Bar
. Please, note, that I need to create many instances of Bar
, so I want to create a class with ByteByddy only once. Could anyone say how to do it?
Byte Buddy creates Java classes, and those classes will need to adhere to the same rules as if you wrote the class manually. As a result, you cannot set a private field from a subclass. You can therefore either: (a) make the field protected, or (b) redefine the class to add the code to the class that declares the field.
As for Byte Buddy, the easiest approach for you would be to use Advice
:
class ConstructorAdvice {
@Advice.OnMethodExit
static void exit(Advice.Field(value = "foo", readOnly = false) Foo foo) {
foo = new Foo();
}
}
You would then apply this advice to all relevant constructors of the class in question, using visit
.