首页 > 解决方案 > 如何使用 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")))))

标签: javabyte-buddybytecode-manipulation

解决方案


看看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获取更多可用于注入上下文信息的注释。


推荐阅读