Maris Novickis
Maris Novickis

Reputation: 23

How to amend the preloaded java class, add fields and methods

I am very new to ByteBuddy API, I have a business requirement to amend (add new methods and new fields) the preloaded java class (SampleA.class)

 final Class<?> newSubclass = new ByteBuddy()
                .redefine(SampleA.class)
                .defineField("newField", String.class, Modifier.PRIVATE)
                .defineMethod("getNewField", String.class, Modifier.PUBLIC)
                .intercept(FieldAccessor.ofField("newField"))
                .defineMethod("setNewField", void.class, Modifier.PUBLIC)
                .withParameters(String.class)
                .intercept(FieldAccessor.ofField("newField"))
                .make()
                .load(ClassLoader.getSystemClassLoader())
                .getLoaded();

With this change, I am getting the exception that this class is already loaded.

Caused by: java.lang.IllegalStateException: Class already loaded: class testbytebuddy.dto.SampleA

My impression from ByteBuddy documentation shows that it is not allowed to add methods or fields when reloading classes. Please correct me if I am wrong and guide me if there is any way or pattern to achieve this business goal.

Upvotes: 2

Views: 191

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44032

Not Byte Buddy, but the JVM disallows it. You would need to add a Java agent and add those fields before the classes are loaded. Byte Buddy can hook into the instrumentation API for this. Have a look into Java agents for this.

Upvotes: 2

Related Questions