Can I override private methods using Byte Buddy?

Can Byte Buddy be used to override a private method of a class? It seems that the entry point to using Byte Buddy is always subclassing an existing class. That said, it is clearly impossible to override the private method of the parent class (at least not in such a way that the overridden method is used in the parent class).

Consider the following example:

public class Foo {
    public void sayHello() {
        System.out.println(getHello());
    }

    private String getHello() {
        return "Hello World!";
    }
}

Foo foo = new ByteBuddy()
    .subclass(Foo.class)
    .method(named("getHello")).intercept(FixedValue.value("Byte Buddy!"))
    .make()
    .load(Main.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
    .getLoaded()
    .newInstance();
foo.sayHello();

      

The output will be "Hello World!" Is there a chance to get "Byte Buddy!" how is the way out?

+3


source to share


1 answer


You are correct that subclassing is the only option for creating classes with Byte Buddy. However, starting with version 0.3, which will be released in the coming weeks, this will change so that you can also override existing classes. Then overriding the class will look like this:

ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy
                                                   .fromInstalledAgent();
new ByteBuddy()
  .redefine(Foo.class)
  .method(named("getHello"))
  .intercept(FixedValue.value("Byte Buddy!"))
  .make()
  .load(Foo.class.getClassLoader(), classReloadingStrategy);
assertThat(foo.getHello(), is("Byte Buddy!"));
classReloadingStrategy.reset(Foo.class);
assertThat(foo.getHello(), is("Hello World"));

      



This approach uses the HotSpot HotSwap mechanism, which is very limited as you cannot add methods or fields. With Byte Buddy version 0.4, Byte Buddy will be able to override unloaded classes and provide an agent linker to implement Java user agents to make such overriding more flexible.

+2


source







All Articles