![](/img/trans.png)
[英]Not able to run ByteBuddy interceptor when @Morph argument is specified
[英]Pass argument to bytebuddy interceptor
我有一個使用Byte Buddy的攔截器,並且想將參數傳遞給攔截器。 我怎樣才能做到這一點?
ExpressionHandler expressionHandler = ... // a handler
Method method = ... // the method that will be intercepted
ByteBuddy bb = new ByteBuddy();
bb.subclass(theClazz)
.method(ElementMatchers.is(method))
.intercept(MethodDelegation.to(MethodInterceptor.class));
.make()
.load(theClazz.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
MethodInterceptor
的攔截方法為:
@RuntimeType
public static Attribute intercept(@Origin Method method, @AllArguments Object[] args) throws Exception {
String name = method.getName();
Class<? extends Attribute> type = (Class<? extends Attribute>) method.getReturnType();
ExpressionHandler expressionHandler= // ???
expressionHandler.attachStuff(name, type);
return expressionHandler;
}
如何將expressionHandler
從構建器傳遞到攔截器方法?
只需使用實例委托而不是類級委托即可:
MethodDelegation.to(new MethodInterceptor(expressionHandler))
與
public class MethodInterceptor {
private final ExpressionHandler expressionHandler;
public MethodInterceptor(ExpressionHandler expressionHandler) {
this.expressionHandler = expressionHandler;
}
@RuntimeType
public Attribute intercept(@Origin Method method, @AllArguments Object[] args) throws Exception {
String name = method.getName();
Class<? extends Attribute> type = (Class<? extends Attribute>) method.getReturnType();
this.expressionHandler.attachStuff(name, type);
return expressionHandler;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.