我正在尝试检测项目中的某些类。当我将代理程序类打包到一个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上。
答案 0 :(得分:0)
使用-javaagent选项,您始终可以确保在安装代理后加载了您的类。
如果将代理程序安装在静态块中,则必须确保在加载要检测的任何类之前执行这段代码。例如。您可以将代理安装在您的main方法中,也可以安装在main方法所在的静态块中。