2016-07-26 158 views
1

我有一个使用Byte Buddy的拦截器,我想将参数传递给拦截器。我怎样才能做到这一点?将参数传递给bytebuddy拦截器

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

只需使用实例代表团而不是类级别代表团:

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; 
    } 
}