raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.23k stars 804 forks source link

How to create a class with updated private field using ByteBuddy? #1692

Closed Stefman87 closed 6 days ago

Stefman87 commented 1 month ago

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?

raphw commented 1 month ago

I already answered you on StackOverflow: https://stackoverflow.com/questions/78849628/how-to-create-a-class-with-updated-private-field-using-bytebuddy/78854737#78854737

Stefman87 commented 1 month ago

@raphw Thank you very much for your help!