2016-07-26 99 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; 
    } 
}