gpt4 book ai didi

java - 将参数传递给 bytebuddy 拦截器

转载 作者:太空宇宙 更新时间:2023-11-04 12:23:40 27 4
gpt4 key购买 nike

我有一个使用 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从构建器到拦截器方法?

最佳答案

简单地使用实例委托(delegate)而不是类级委托(delegate):

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

关于java - 将参数传递给 bytebuddy 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38585748/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com