byte-buddy
byte-buddy copied to clipboard
How to create a class with updated private field using ByteBuddy?
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?
I already answered you on StackOverflow: https://stackoverflow.com/questions/78849628/how-to-create-a-class-with-updated-private-field-using-bytebuddy/78854737#78854737
@raphw Thank you very much for your help!