byte-buddy icon indicating copy to clipboard operation
byte-buddy copied to clipboard

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

Open Stefman87 opened this issue 1 year ago • 2 comments

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?

Stefman87 avatar Aug 08 '24 19:08 Stefman87

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 avatar Aug 09 '24 22:08 raphw

@raphw Thank you very much for your help!

Stefman87 avatar Aug 10 '24 05:08 Stefman87