java - 使用 bytebuddy 定义字段后如何建议原始类的构造函数

标签 java instrumentation byte-buddy

我正在尝试为类定义一个字段并根据建议使用它。我用普通方法尝试了这个,但我不能将它与构造函数一起使用。我尝试使用

.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/

相关文章:

javascript - 重新定义window.console函数时保持原路径位置

java - 当我使用 java.lang.instrument.Instrumentation#redefineClasses() 时,我应该将数组传递给函数吗?

java - Byte Buddy 和 OSGi Weaving Hook

performance - 当我只需要基本覆盖数据时,如何提高 OpenCover 性能?

java - 具有唯一 ID 的 ArrayBlockingQueue

java - 将报表名称存储在 Interface 、 Enum 中,还是作为报表处理程序类中的常量?

java - 获取与谓词匹配的元素的索引

java - 方法委托(delegate)和添加字段

java - 如何使用 byte buddy 在运行时有效地将接口(interface)与 POJO 关联?

java - $assertionsDisabled 和 javac 标准合规性