有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    您可以向MethodDelegation提供匹配器,以缩小要考虑的方法范围:

    MethodDelegation.withDefaultConfiguration().filter(...).to(...)
    

    至于MethodCall,您需要指定要包括哪些参数,foo接受两个参数。由于原始参数似乎是等效的,因此可以设置:

    MethodCall.invoke(fooMethod).on(service).withAllArguments();