我正在尝试创建一个 java 代理来测量使用 byte buddy lib 的方法的执行时间而不更改 main 方法。我按照教程创建以下代码。 执行此 MonitorInspector 时必须给出执行所花费的时间。但它不工作只给出如下输出。
预维护
主类
有什么办法可以解决这个问题。 请帮我解决这个问题。
这是我的代码.. AgentTest(代理的这段代码)
class AgentTest {
public static void premain(String arguments, Instrumentation ins) {
System.out.println("Premain");
new AgentBuilder.Default()
.type(ElementMatchers.nameEndsWith("Timed"))
.transform((builder, type, classLoader, module)->builder.method(ElementMatchers.any()).intercept(MethodDelegation.to(MonitorInterceptor.class))
).installOn(ins);
}}
监控检查器
class MonitorInterceptor {
@RuntimeType
public static Object intercept(@Origin Method method,@SuperCall Callable<?> callable) throws Exception {
long start = System.currentTimeMillis();
try {
return callable.call();
} finally { System.out.println(method + " took " +(System.currentTimeMillis()-start));
}}}
主类
public class SampleClass {
public static void main(String[] args) {
System.out.println("Main Class");
Methods.test(0);
}}
最佳答案
您还可以通过使用 Advice
来实现这一点,它使用代码内联并且应该会带来更好的运行时性能:
class TimerAdvice {
@Advice.OnMethodEnter
static long enter() {
return System.currentTimeMillis();
}
@Advice.OnMethodExit(onException = Throwable.class)
static void exit(@Advice.Origin String method, @Advice.Enter long start) {
System.out.println(method + " took " + (System.currentTimeMillis() - start));
}
}
并应用建议
new AgentBuilder.Default()
.type(ElementMatchers.nameEndsWith("Timed"))
.transform((builder, type, classLoader, module) ->
builder.visit(Advice.to(TimerAdvice).on(ElementMatchers.any()));
);
这样,时间也不会显示在堆栈跟踪中。
关于java - 使用 Java 代理和 byte-buddy 测量执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47843523/