我正在尝试在项目中检测某些类。当我将代理程序类打包到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上。
我正在尝试在项目中检测某些类。当我将代理类打包到jar中并通过-javaagent使用它时,它可以正常工作。公共静态无效premain(String arguments,Instrumentation ...
使用-javaagent选项,您始终可以确保在安装代理后加载了您的类。