![](/img/trans.png)
[英]How to add a field to a class in ByteBuddy and set / get that value in a method interceptor
[英]Bytebuddy method interceptor not working with self defined class
我是 bytebuddy 的新手,給定 Foo 和 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;
}
}
然后,如果我嘗試重新定義 Foo 的 hello,它會起作用,但我無法讓它對 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();
它給出了錯誤:
java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)
我怎樣才能使它適用於 Bar?
正如 Holger 指出的那樣:您不能將字段添加到已加載的類中。 如果您將方法委托設置為靜態方法,則不會出現問題。
例如,在靜態方法中,您可以將實例的弱映射(通過@Origin)保存到這些對象並從那里讀取返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.