我正在尝试将 Cglib 代理转换为 ByteBuddy。Cglib 有net.sf.cglib.proxy.Proxy接口来拦截所有的方法调用。我检查了 ByteBuddy 的文档,但找不到这样的例子。对于我用 ByteBuddy 实例化的每个对象,如果没有这样的接口,我就会再次重复同样的事情。ByteBuddy 有没有更好的方法来做到这一点?
这是我的示例代码片段:
服务:
public class MyService {
public void sayFoo() {
System.out.println("foo");
}
public void sayBar() {
System.out.println("bar");
}
}
拦截器:
public class MyServiceInterceptor {
public void sayFoo(@SuperCall Callable<Void> zuper) {
try {
zuper.call();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sayBar(@SuperCall Callable<Void> zuper) {
try {
zuper.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试:
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.dynamic.ClassLoadingStrategy;
import net.bytebuddy.instrumentation.MethodDelegation;
import net.bytebuddy.instrumentation.method.matcher.MethodMatchers;
public class Main {
public static void main(String[] args) throws Exception {
ByteBuddy buddy = new ByteBuddy(ClassFileVersion.forCurrentJavaVersion());
Class<? extends MyService> serviceClass =
buddy.subclass(MyService.class)
.method(MethodMatchers.named("sayFoo").or(MethodMatchers.named("sayBar")))
.intercept(MethodDelegation.to(new MyServiceInterceptor()))
.make()
.load(Main.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
MyService service = serviceClass.newInstance();
service.sayFoo();
service.sayBar();
}
}