gpt4 book ai didi

java - 有没有办法从 ByteBuddy 的拦截器中通过 MethodDescription 调用方法?

转载 作者:行者123 更新时间:2023-12-02 00:27:18 25 4
gpt4 key购买 nike

我正在实现一个代理,使加载的类隐式实现一个接口(interface)。接口(interface)中的方法,由代理实现,以自定义的方式调用原始类方法,并用特殊的注释进行标记。但事实证明,在 AgentBuilder.Transformer 中加载的类仍然不存在。然而,拦截器内的代码是在类实际加载后执行的。因此拦截器内的代码可以与类方法一起使用。我可以使用 MethodDescription 对象调用该方法吗?

public class CustomTransformer implements AgentBuilder.Transformer {

public static class InstantiateInterceptor {

private final Collection<MethodDescription> methodDescription;

InstantiateInterceptor(Collection<MethodDescription> methodDescription) {
this.methodDescription = methodDescription;
}

public Object intercept(@This Object self) {
//
// Call method by descriptions somewhere here
//
return null;
}
}

@Override
public DynamicType.Builder<?> transform(
DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {

try {

List<MethodDescription> cacheableMethods =
typeDescription.getDeclaredMethods().stream()
.filter(t -> t.getDeclaredAnnotations()
.isAnnotationPresent(EnhanceMarker.class))
.collect(Collectors.toList());

return builder
.implement(HasField.class)
.define(HasField.class.getMethod("value"))
.intercept(MethodDelegation
.to(new InstantiateInterceptor(cacheableMethods)));
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}

return builder;
}
}

我可能可以通过名称从 @This 对象获取该方法。但它需要参数类型列表,并且我只能获取 ParameterDescription 类对象列表,并且它不返回参数类型。

最佳答案

如果该方法在 @This 实例上可用,为什么不直接调用它而不进行反射呢?或者这个方法是生成的吗?在这种情况下,请在接口(interface)中定义签名,实现该接口(interface)并读取该接口(interface)上的 @This 实例。

如果您想调用 super 方法,您可以使用 @Super 注释的实例执行相同的操作,其中 Byte Buddy 创建适当的代理。

关于java - 有没有办法从 ByteBuddy 的拦截器中通过 MethodDescription 调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044005/

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