gpt4 book ai didi

java - 用 ByteBuddy 修饰方法

转载 作者:行者123 更新时间:2023-12-02 12:03:13 25 4
gpt4 key购买 nike

如何定义一个方法,然后用 ByteBuddy 装饰它(多次)?这是我的例子

Builder<Object> builder = new ByteBuddy().subclass(Object.class).name("Dynamic");
builder = builder.defineMethod("method", void.class, Visibility.PUBLIC)
.intercept(MethodDelegation.to(new Object(){

@RuntimeType
public void intercept(@This Object o) {
System.out.println("Executing code...");
}

}));

builder = builder.method(ElementMatchers.named("method")).
intercept(MethodDelegation.to(new Object(){

@RuntimeType
public void intercept(@This Object o) {
System.out.println("Executing other code...");
}

}));

try {
Class cls = builder.make()
.load(StructClassBuilder.class.getClassLoader())
.getLoaded();

Object obj = cls.newInstance();
cls.getDeclaredMethod("method").invoke(obj, args);
} catch (Exception e1) {
e1.printStackTrace();
}

输出为

Executing other code...

我希望输出是

Executing code...

Executing other code...

谢谢

最佳答案

一种选择是使用 MethodDelegation.to(...).addThen(...) 方法链接您的拦截器。

public class ByteBuddyTest {

public static void main(String[] args) throws Exception {
DynamicType.Builder<Object> builder = new ByteBuddy().subclass(Object.class).name("Dynamic");
builder = builder
.defineMethod("method", void.class, Visibility.PUBLIC)
.intercept(MethodDelegation.to(Interceptor1.class).andThen(MethodDelegation.to(Interceptor2.class)));

try {
Class<?> clazz = builder.make().include().load(ByteBuddyTest.class.getClassLoader()).getLoaded();

Object obj = clazz.newInstance();
clazz.getDeclaredMethod("method").invoke(obj, args);
} catch (Exception e1) {
e1.printStackTrace();
}
}

public static class Interceptor1 {

public static void intercept() {
System.out.println("Executing code...");
}
}

public static class Interceptor2 {

public static void intercept() {
System.out.println("Executing other code...");
}
}
}

关于java - 用 ByteBuddy 修饰方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com