java - 如何使用 ByteBuddy 拦截方法,就像在 CGLIB 中使用 MethodInterceptor 调用 MethodProxy.invokeSuper(...)
问题描述
我想用 ByteBuddy 截取一些方法。当我使用时 InvocationHandlerAdapter.of(invocationHandler)
,我无法调用超级方法。持有对象实例不适合我的情况。我想要和下面的 CGLIB 完全一样。
(MethodInterceptor)(obj, method, args, proxy)->{
// to do some work
Object o = proxy.invokeSuper(obj,args);
// to do some work
return o;
}
我怎样才能像这样在 ByteBuddy 中实现拦截方法?
我尝试MethodCall
了 type ofImplemetation
但它没有解决我的问题。MethodCall.invokeSuper()
因为在这种情况下我无法管理。
.intercept(MethodCall
.run(() -> System.out.println("Before"))
.andThen(MethodCall.invokeSuper())
.andThen(MethodCall
.run((() -> System.out.println("After")))))
解决方案
看看MethodDelegation
,例如:
public class MyDelegation {
@RuntimeType
public static Object intercept(@SuperCall Callable<?> superCall) throws Exception {
// to do some work
Object o = superCall.call();
// to do some work
return o;
}
}
然后使用:
.intercept(MethodDelegation.to(MyDelegation.class))
您可以查看 javadoc 以MethodDelegation
获取更多可用于注入上下文信息的注释。
推荐阅读
- ruby-on-rails - 如何在 render_to_string 之后重定向到 html 页面?
- c# - 只允许在 WPF 数据网格中选中一个单选按钮
- flask - 酒馆授权
- arrays - 数组包含来自另一个数组的每个值?
- javascript - 函数中的Javascript tyepscrypt错误
- groovy - 在 Groovy 中使用 JavaConfig stepScope() 会导致 NullPointerException
- javascript - HTML 表单:将 div 设为提交按钮
- php - 使用 PHP Simple HTML Parser 查找前面的元素
- javascript - 使用 RegEx 删除字符串中“/”后的空格
- html - CSS将2个表单字段彼此相邻