2

我有一个使用 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将构建器传递给拦截器方法?

4

1 回答 1

1

只需使用实例委托而不是类级委托:

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;
  }
}
于 2016-07-26T18:02:28.113 回答