【发布时间】:2019-11-09 18:44:50
【问题描述】:
我正在尝试在项目中检测一些类。当我将代理类打包到一个 jar 中并通过 -javaagent 使用它时,它工作正常。
public static void premain(String arguments, Instrumentation instrumentation) {
new AgentBuilder.Default()
.type(ElementMatchers.nameStartsWith("com.cn."))
.transform((builder, type, cl, m) -> builder
.method(ElementMatchers.isAnnotatedWith(Retryable.class))
.intercept(to(Retry.class)))
.installOn(instrumentation);
}
当我尝试直接在项目中运行它时,检测有时会失败。 (我在测试类的静态块中初始化 bytebuddy)。
static {
Instrumentation inst = ByteBuddyAgent.install();
new AgentBuilder.Default()
.type(ElementMatchers.nameStartsWith("com.cn."))
.transform((builder, type, cl, m) -> builder
.method(ElementMatchers.isAnnotatedWith(Retryable.class))
.intercept(to(Retry.class)))
.installOn(inst);
}
例如,当我添加此测试时,我的代码不再被拦截。 对 try/catch 做同样的事情。
RuntimeException e = Assertions.assertThrows(RuntimeException.class, () -> f.doit("doit foo"));
是否有一种安全的方法可以在没有 -javaagent 的情况下检测同一项目中的类?
项目在 OpenJdk11 上。
【问题讨论】:
-
您是否尝试向代理生成器添加侦听器以查看是否仍然发现了相关类型或是否存在错误?有没有检查block中的安装是否抛出异常?
标签: java byte-buddy