相关疑难解决方法(0)

Byte-Buddy:方法拦截 InvoiceHandler 与 MethodDelegation 到 GeneralInterceptor

我使用 Byte-Buddy 动态生成 Java 接口方法的实现,并将对这些方法的调用委托给现有代理对象的单个方法。

第一个版本的灵感来自如何使用 ByteBuddy 创建动态代理

它使用反射InvocationHandler

即具体代理类:

  • 实现接口InvocationHandler
  • 覆盖该方法invoke()

这很好用。

然后重新阅读Github 上的 Byte-Buddy 自述文件,MethodDelegation我发现了使用“GeneralInterceptor”的替代版本。

即具体代理类:

  • 有一个用注释标记的方法RuntimeType

这也很好用!

下面的代码片段演示了这两种技术。

Class<? extends Object> clazz = new ByteBuddy()
    .subclass(serviceSuperClass)
    .name(className) 
    // use a Reflection InvocationHander for the methods of serviceInterfaceOne
    .implement(serviceInterfaceOne)
    .defineField(invocationHandler, MyProxy.class, Visibility.PUBLIC)
    .method(isDeclaredBy(serviceInterfaceOne))
    .intercept(InvocationHandlerAdapter.toField(invocationHandler))
    // use a Byte-Buddy "GeneralInterceptor" for the methods of serviceInterfaceTwo
    .implement(serviceInterfaceTwo)
    .defineField(generalInterceptor, MyProxy.class, Visibility.PUBLIC)
    .method(isDeclaredBy(serviceInterfaceTwo))
    .intercept(MethodDelegation.toField(generalInterceptor))
    //
    .make ()
    .load(classLoader)
    .getLoaded();
Run Code Online (Sandbox Code Playgroud)
public class MyProxy implements …
Run Code Online (Sandbox Code Playgroud)

java byte-buddy

5
推荐指数
1
解决办法
1350
查看次数

标签 统计

byte-buddy ×1

java ×1