gpt4 book ai didi

java - ByteBuddy MethodDelegation 在 Java Agent 中不起作用

转载 作者:行者123 更新时间:2023-11-30 07:56:08 41 4
gpt4 key购买 nike

我有一个 premain() ,其中所有用特定注释注释的方法都应该委托(delegate)给特定的类。一般来说,我看起来像这样:

public static void premain( final String agentArguments, final Instrumentation instrumentation ) {

CountingInterception ci = new CountingInterception();

new AgentBuilder.Default()
.type(ElementMatchers.isAnnotatedWith(com.codahale.metrics.annotation.Counted.class))
.transform((builder, type, classLoader, module) ->
builder.method(ElementMatchers.any())
.intercept(MethodDelegation.to(ci))
).installOn(instrumentation);
}

使用调试器显示这部分已处理,但如果调用带注释的方法,则没有任何反应。

CountingInterception 看起来像这样

public class CountingInterception {

@RuntimeType
public Object intercept(@DefaultCall final Callable<?> zuper, @Origin final Method method, @AllArguments final Object... args) throws Exception {

String name = method.getAnnotation(Counted.class).name();
if (name != null) {
// do something
}

return zuper.call();
}
}

感谢任何提示!

使用 ByteBuddy 1.6.9

最佳答案

为了实现我想做的事情,进行了以下更改:

在预维护中:

CountingInterception ci = new CountingInterception();

new AgentBuilder.Default()
.type(declaresMethod(isAnnotatedWith(Counted.class)))
.transform((builder, type, classLoader, module) -> builder
.method(isAnnotatedWith(Counted.class))
.intercept(MethodDelegation.to(ci).andThen(SuperMethodCall.INSTANCE))
).installOn(instrumentation);

在 CountingInterception 中:

public void interceptor(@Origin final Method method) throws Exception {

String name = method.getAnnotation(Counted.class).name();
if (name != null) {
// do something
}

}

关于java - ByteBuddy MethodDelegation 在 Java Agent 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558942/

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