Bytebuddy代理以打印方法经过的时间
我正在尝试测量某些特定类别的某些方法的时间。我正在使用Bytebuddy,并且创建了以下interceptor类:
public class TimingInterceptor {
@RuntimeType
public static Object intercept(@Origin Method method,
@SuperCall Callable<?> callable) {
long start = System.currentTimeMillis();
try {
return callable.call();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(method + " took " + (System.currentTimeMillis() - start));
}
return null;
}
}
这是我正在使用的Java代理类:
public class TimerAgent {
public static void premain(String arguments,
Instrumentation instrumentation) {
new AgentBuilder.Default()
.type(ElementMatchers.nameStartsWith("BP")) // This is because I used the prefix BP to name methods I need to measure
.transform((builder, type, classLoader, module) ->
builder.method(ElementMatchers.any())
.intercept(MethodDelegation.to(TimingInterceptor.class))
).installOn(instrumentation);
}
}
我运行了一个测试应用程序,包括以“ BP”为前缀命名的方法,以及类TimingInterceptor中的消息,指示该方法持续时间未显示。
有些想法?
示例完整代码:
- 代理:
- 测试应用程序: https://github.com/rauldevilla /字节buddy-lab
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要调试问题,最好向您的代理注册
AgentBuilder.listener
始终是一个好主意。 JVM中的仪器API抑制了在仪器期间抛出的所有异常,听众允许您捕获这些异常并打印它们。对于这样的“围绕”仪器,我通常建议使用
建议
,因为它不会对类加载器层次结构进行假设,您在使用委托时需要明确地解决这些假设。To debug issues, it is always a good idea to register an
AgentBuilder.Listener
with your agent. The instrumentation API in the JVM suppresses all exceptions that are thrown during an instrumentation and the listener allows you to catch those exceptions and to print them for example.For such "around" instrumentation, I generally recommend using
Advice
as it does not make assumptions on class loader hierarchies which you need to address explicitly when using delegation.