Liviu Carausu
Liviu Carausu

Reputation: 65

redefine static methods with ByteBuddy

Can homebody help me please to give me a hint how to redefine static methods using byte-buddy 1.6.9 ?

I have tried this :

public class Source {
    public  static String hello(String name) {return null;}
}


public class Target {
    public static String hello(String name) {
        return "Hello" + name+ "!";
    }
}
String helloWorld = new ByteBuddy()
                .redefine(Source.class)               
                .method(named("hello"))
                .intercept(MethodDelegation.to(Target.class))
                .make()
                .load(getClass().getClassLoader())
                .getLoaded()
                .newInstance()
                .hello("World");

I got following Exception :

Exception in thread "main" java.lang.IllegalStateException: Cannot inject already loaded type: class delegation.Source

Thanks

Upvotes: 1

Views: 2257

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44077

Classes can only be loaded once by each class loader. In order to replace a method, you would need to use a Java agent to hook into the JVM's HotSwap feature.

Byte Buddy provides a class loading strategy that uses such an agent, use:

.load(Source.class.getClassLoader(), 
      ClassReloadingStrategy.fromInstalledAgent());

This does however require you to install a Java agent. On a JDK, you can do so programmatically, by ByteBuddyAgent.install() (included in the byte-buddy-agent artifact). On a JVM, you have to specify the agent on the command line.

Upvotes: 1

Related Questions