定义方法,调用和拦截器并委托ByteBuddy来定位?

时间:2019-10-24 14:56:39

标签: java code-generation byte-buddy

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

想要创建一个新的包装器类,

  • 具有单个方法_foo一个附加参数
  • _foo执行委托给拦截器,返回将被忽略
  • 最后,将调用委托给foo上的目标service

以某种方式,我没有这样做:

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

答案 0 :(得分:1)

您可以为firebase.auth().createUserWithEmailAndPassword(email, password).then(cred=>{ cred.user.updateProfile({ displayName: first_name + " " + last_name }) }) .catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; window.alert("Error: " + errorMessage); // ... }); 提供一个匹配器,以缩小要考虑的方法:

MethodDelegation

对于MethodDelegation.withDefaultConfiguration().filter(...).to(...) ,您需要指定要包含的参数,MethodCall接受两个参数。由于您的原始参数似乎是等效的,因此可以设置:

foo
相关问题