我使用Buddy动态生成Java接口方法的实现,并将对这些方法的调用委托给现有代理对象的单个方法。
第一个版本是受如何使用ByteBuddy创建动态代理的启发
它使用反射InvocationHandler。
即具体的代理类:
InvocationHandlerinvoke()这个很好用。
然后重新阅读字节- Github上的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();public class MyProxy implements InvocationHandler {
@Override
public Object invoke(Object serviceImpl, Method method, Object[] args) throws Throwable {
return null;
}
@RuntimeType
public Object intercept(@AllArguments Object[] allArguments,
@Origin Method method) {
return null;
}
}从高层次的角度来看,这两种技术都允许我做同样的事情:
也就是说,将给定的动态创建的方法拦截到现有的具体方法。
这两种解决方案都很优雅,所需的代码数量也是相似的。
问题是:有什么理由选择哪一个而不是另一个呢?比如表演?功能?
发布于 2020-02-21 08:00:06
在这种形式的使用中,除了委托可以连接到任何(静态或非静态)方法之外,没有真正的区别,而调用处理程序适配器只连接Java代理API的实现。如果您已经实现了这样的代理处理程序,并且希望与Buddy一起重用它们,那么它主要是指。
字节Buddy的处理程序允许比处理程序API更灵活,这可以提高性能,例如,如果您知道预期的参数,就可以避免数组装箱。它还允许调用调用处理程序API不支持的默认方法实现等不同机制。
https://stackoverflow.com/questions/60317919
复制相似问题