我正在尝试为类定义一个字段并根据建议使用它。我用普通方法尝试了这个,但我不能将它与构造函数一起使用。我尝试使用
.constructor(ElementMatchers.any())
.intercept(SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(MethodListener.class)))
但随后建议未运行。我的代码如下..
代理
new AgentBuilder.Default()
.with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
.type(ElementMatchers.nameContains("BalConnectorCallback"))
.transform((builder, typeDescription, classLoader, module) -> builder
.defineField("contextTimer", Timer.Context.class)
.method(ElementMatchers.any())
.intercept(Advice.to(MethodListener.class))
).installOn(instrumentation);
这是我的建议
public class MethodListener {
@Advice.OnMethodEnter
public static void enter(@Advice.Origin String method,
@Advice.AllArguments Object[] para,
@Advice.FieldValue(value = "contextTimer", readOnly = false) Timer.Context contextTimer)
throws Exception {
if (getMethodName(method).equals("BalConnectorCallback")) {
contextTimer = metricServer.getResponsesTime().start();
}
}
@Advice.OnMethodExit
public static void exit(@Advice.Origin String method,
@Advice.FieldValue("contextTimer") Timer.Context contextTimer)
throws Exception {
if (getMethodName(method).equals("done")) {
contextTimer.stop();
}
}
}
如何建议构造函数定义字段?
最佳答案
您好,使用
解决了这个问题.constructor(ElementMatchers.any())
.intercept(Advice.to(ConstructorAdvice.class))
并为构造函数创建了另一个建议,如下
public class ConstructorAdvice {
@Advice.OnMethodExit
public static void enter(@Advice.Origin String method,
@Advice.AllArguments Object[] para,
@Advice.FieldValue(value = "contextTimer", readOnly = false) Timer.Context contextTimer)
throws Exception {
if (getMethodName(method).equals("BalConnectorCallback")) {
contextTimer = metricServer.getResponsesTime().start();
}
}
关于java - 使用 bytebuddy 定义字段后如何建议原始类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48782971/