Liviu Carausu
Liviu Carausu

Reputation: 65

Redefine a class using byte-buddy

I want to redefine the Source class which is already defined in an existing framework. I want to automatically replace the original instances of the Source class with my enhanced class. I do not have access to the code that creates the Source objects so the class substitution must perform automatically under the hood. Is it possible to do this using byte-buddy ?

    ByteBuddyAgent.install();
    Source source = new ByteBuddy()
            .subclass(Source.class)
            .method(named("hello")).intercept(MethodDelegation.to(Target.class))
            .defineMethod("myNewMethod", void.class).intercept(MethodDelegation.to(Target.class))
            .make()
            .load(Source.class.getClassLoader(),
                    ClassReloadingStrategy.fromInstalledAgent())
            .getLoaded()
            .newInstance();

Upvotes: 1

Views: 3098

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44007

It is possible to redefine a class using Byte Buddy. To do so, you would use the ByteBuddy::redefine or ByteBuddy::rebase methods instead of subclassing. The most canonical way to use these features is by defining a Java Agent for what you can use the AgentBuilder.

Upvotes: 2

Related Questions