我有一個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 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
您可以提供匹配器來MethodDelegation
縮小要考慮的方法的范圍:
MethodDelegation.withDefaultConfiguration().filter(...).to(...)
至于您的MethodCall
,您需要指定要包含哪些參數,foo
需要兩個參數。由于您的原始參數似乎是等效的,因此您可以設置:
MethodCall.invoke(fooMethod).on(service).withAllArguments();
添加回答
舉報
0/150
提交
取消