java - 使用不带 -javaagent 参数的 ByteBuddy Java 代理
问题描述
我正在尝试在项目中检测一些类。当我将代理类打包到一个 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 上。
解决方案
使用 -javaagent 选项,您将始终确保在安装代理后加载您的类。
如果将代理安装在静态块中,则必须确保在加载要检测的任何类之前执行这段代码。例如。您可以将代理安装在您的主要方法中或主要方法所在的静态块中。
推荐阅读
- html - 如何在不使用表格的情况下将图像添加到 HTML/CSS 日历?
- javascript - 数组未清空
- sql - 如何在第二行sql server中传递第一行列值一些列?
- node.js - 将它们作为查询传递给model.find()时,如何忽略带有空字符串的值?
- java - 如何在 Excel 文件中添加新行?
- javascript - 在 javascript 迷宫中显示数组
- java - 使用不带 ssl 的 appassets.androidplatform.net(用于通过 http 发送 ajax 请求)
- laravel - 当我有大量数据时,为什么我的数据表会起作用?
- python - PySpark 铸造混乱 - 尽管没有抱怨铸造,但列没有铸造成 Double
- javascript - 是否可以在给定位置触发滚动事件,就好像光标在那里并且用户正在滚动一样?