java用ByteBuddy定义一个方法、调用、拦截器和委托给目标?
我有一个对象service
,它有几个方法,其中一个方法是foo(arg1, arg2)
要创建一个新的包装器类:
- 有一个方法
_foo
和一个附加参数 - 将
_foo
执行委托给拦截器,将忽略返回 - 最后,在
service
上委托对目标foo
的调用李>
不知何故,我未能做到这一点:
final List<Class<?>> parameters =
Arrays.stream(fooMethod.getParameters())
.map(Parameter::getType)
.collect(Collectors.toList());
parameters.add(AdditionalParameter.class);
final DynamicType.Unloaded unloadedType = new ByteBuddy()
.subclass(Object.class)
.implement(interfaceType)
.name(service.getClass().getSimpleName() + "Dynamic")
.defineMethod(
"_" + methodName,
resolveReturnType(fooMethod),
Modifier.PUBLIC)
.withParameters(parameters)
.intercept(to(fooInterceptor).andThen(
MethodCall.invoke(fooMethod).on(service)
))
.make();
fooInterceptor
是一个InvocatiomHandler
实例:
public class FooInterceptor implements InvocationHandler {
public Object invoke(
@This final Object proxy,
@Origin final Method method.
@AllArguments final Object[] args) {
...
}
}
异常表示我的fooService
“不接受0个参数”
我可以从拦截器调用service.foo()
但不使用反射吗?我不能这样做(但还没有扮演那个角色)
帮忙?🙏
编辑:我无法控制service
中的方法,因此我不能简单地将to(service)
与截取调用一起使用;可能有这样一种情况,ByteBuddy无法找到匹配的方法
EDIT2:如果我能告诉ByteBuddy要绑定的目标方法的名称,那就太棒了。然后我可以在给出提示的情况下使用to(service)
# 1 楼答案
您可以向
MethodDelegation
提供匹配器,以缩小要考虑的方法范围:至于
MethodCall
,您需要指定要包括哪些参数,foo
接受两个参数。由于原始参数似乎是等效的,因此可以设置: