定义一个方法,调用和拦截器并委托给 ByteBuddy 的目标?

Define a method, call and interceptor and delegate to target with ByteBuddy?

我有一个对象 service,它有几种方法,其中一种方法是 foo(arg1, arg2)

想要创建一个新的包装器 class 那:

不知何故,我没有这样做:

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 "does not accept 0 arguments".

我可以从拦截器调用 service.foo() 但不使用反射吗?我无法这样做(但还没有玩那个部分)。

帮忙?

编辑:我无法控制 service 中的方法,所以我不能简单地使用 to(service) 进行拦截调用;可能会出现字节好友找不到匹配方法的情况

EDIT2:如果我可以 'tell' ByteBuddy 要绑定的目标方法的名称,那就太棒了。然后我可以使用 to(service) 给定的提示。

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

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

至于您的 MethodCall,您需要指定要包含的参数,foo 有两个参数。由于您的原始参数似乎是等价的,您可以设置:

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