我有一个使用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
从构建器传递给拦截器方法?
答案 0 :(得分:0)
只需使用实例委派而不是类级委派:
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;
}
}