将参数传递给 bytebuddy 拦截器
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
从构建器传递到拦截器方法?
简单地使用实例委托而不是class级委托:
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;
}
}
我有一个使用 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
从构建器传递到拦截器方法?
简单地使用实例委托而不是class级委托:
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;
}
}