gpt4 book ai didi

java - 我用 Bytebuddy 添加的方法没有被调用,但没有错误

转载 作者:行者123 更新时间:2023-12-02 04:40:48 24 4
gpt4 key购买 nike

我正在尝试使用 Bytebuddy 在运行时向现有类添加一个方法,我没有收到任何错误,但没有得到预期的输出。这是我的经纪人:

public class Agent {

public static void premain(String arguments, Instrumentation instrumentation) {

System.out.println("Agent for add a method ");

new AgentBuilder.Default()
.with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
.type((ElementMatchers.nameContains("cup")))
.transform((builder, typeDescription, classLoader, module) -> builder
.defineMethod("method3", void.class, Visibility.PUBLIC)
.intercept(MethodDelegation.to(AddMethod.class))
.method(ElementMatchers.any())
.intercept(SuperMethodCall.INSTANCE
.andThen(MethodCall.invoke(ElementMatchers.nameContains("method3"))))
).installOn(instrumentation);

}
}

预期的输出应该是这个函数:

    public static void method3() throws Exception {

System.out.println("This is method 3");

}

运行时命令行的输出只是

Agent for add a method
hello world

这是我正在尝试检测的 java 文件。

public class cuppy {
public static void main (String args [])
{
method1();
}

public static void method1 ()
{
System.out.println("hello world);
}
}

最佳答案

我不是最聪明的。

它在调用对象时调用该函数,而我从未在我的 cuppy 类中调用过对象。

一旦我将 cuppy 主函数更改为

 cuppy cup = new cuppy();
cup.method1();

它达到了我的预期。

关于java - 我用 Bytebuddy 添加的方法没有被调用,但没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56518710/

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