简体   繁体   中英

Bytebuddy method interceptor not working with self defined class

I am new to bytebuddy, given class Foo and Bar:

class Foo {
  public String hello() {
    return "greeting"
  }
}

class Bar {
  public Greet hello() {
    return new Greet("greeting");
  }
}

class Greet {
  private String message;
  Greet(String message) {
    this.message = message;
  }
}

Then if I try to redefine Foo's hello, it works, but I cannot make it work for Bar:


//worked
ByteBuddyAgent.install();
new ByteBuddy()
  .redefine(Foo.class)
  .method(named("hello"))
  .intercept(FixedValue.value("modified greeting"))
  .make()
  .load(getClass().getClassLoader(), ClassReloadingStrategy.fromInstalledAgent())
  .getLoaded()
  .newInstance()
  .hello();

//gives error
ByteBuddyAgent.install();
new ByteBuddy()
  .redefine(Bar.class)
  .method(named("hello"))
  .intercept(FixedValue.value(new Greeting("modified greeting")))
  .make()
  .load(getClass().getClassLoader(), ClassReloadingStrategy.fromInstalledAgent())
  .getLoaded()
  .newInstance()
  .hello();

it gives error:

java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)

How can I make it work for Bar?

As Holger points put: you cannot add fields to loaded classes. If You set a Method delegation to a static method, the problem will not occur.

In the static method, you could for example keep a weak map of instances (via @Origin) to these objects and read the return value from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM