簡體   English   中英

如何使用 ByteBuddy 攔截方法,就像在 CGLIB 中使用 MethodInterceptor 調用 MethodProxy.invokeSuper(...)

[英]How to intercept method with ByteBuddy as in CGLIB with MethodInterceptor for calling MethodProxy.invokeSuper(…)

我想用 ByteBuddy 截取一些方法。 當我使用InvocationHandlerAdapter.of(invocationHandler)時,我無法調用超級方法。 持有 object 實例不適合我的情況。 我想要和下面的 CGLIB 完全一樣。

(MethodInterceptor)(obj, method, args, proxy)->{
   // to do some work
   Object o = proxy.invokeSuper(obj,args);
   // to do some work
   return o;
}

我怎樣才能像這樣在 ByteBuddy 中實現攔截方法?

我嘗試了MethodCall類型的實現Implemetation但它沒有解決我的問題。 因為在這種情況下我無法管理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))

您可以查看MethodDelegation的 javadoc 以獲取更多可用於注入上下文信息的注釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM