[英]Redefine methods with ByteBuddy
我正在嘗試使用 ByteBuddy 重新定義一些方法。 當我使用 FixedValue.value() 攔截方法時,沒問題。 但是使用攔截器攔截方法時,編譯器會拋出 UnsupportedOperationException。
我想覆蓋“Foo.nothing()”方法來打印一些東西。
public class Foo {
public String getHello() {
return "not redefined hello!";
}
public String getBye() {
return "not redefined Bye!";
}
public void nothing() {}
}
這是我的攔截器:
public class GeneralInterceptor {
@RuntimeType
public Object intercept(@AllArguments Object[] allArguments,
@Origin Method method) {
System.out.println("asdfasdf");
return null;
}
}
這是我重新定義的代碼
public class RedefineTest {
ClassReloadingStrategy classReloadingStrategy;
@BeforeEach
public void init() {
ByteBuddyAgent.install();
classReloadingStrategy = ClassReloadingStrategy.fromInstalledAgent();
}
@Test
public void redefineTest() {
// okay
new ByteBuddy()
.redefine(Foo.class)
.method(named("getHello"))
.intercept(FixedValue.value("ByteBuddy Hello!"))
.make()
.load(Foo.class.getClassLoader(), classReloadingStrategy);
// error
new ByteBuddy()
.redefine(Foo.class)
.method(named("nothing"))
.intercept(MethodDelegation.to(new GeneralInterceptor()))
.make()
.load(Foo.class.getClassLoader(), classReloadingStrategy);
Foo foo = new Foo();
System.out.println(foo.getHello());
System.out.println(foo.getBye());
foo.nothing();
}
}
我解決了!
public class GeneralInterceptor {
@RuntimeType
public static Object intercept(@AllArguments Object[] allArguments) {
System.out.println("asdfasdf");
return null;
}
}
並改變
intercept(MethodDelegation.to(new GeneralInterceptor())
到
intercept(MethodDelegation.to(GeneralInterceptor.class)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.