如何在加载 class' 字节码之前对其进行操作?

How to manipulate a class' bytecode just before it is loaded?

我正在尝试找到一种方法来在 class 加载之前操纵它的字节码(在运行时)。我需要这样做,因为操作取决于 main 之前不存在的东西(并且可能在加载主题 class 之前)。

我已经查看了 java 个代理。 premain方法在这里显然不适用,因为它是在main之前执行的,这意味着它不能依赖于main中设置的东西。 另一个选项似乎是 agentmainmanually loading the agent at runtime。现在的问题是,在较新的版本 (9+) 中,执行此操作所需的依赖项 (tools.jar) 似乎不再存在。

现在,我想知道在运行时的特定时间点或就在加载 class 之前操作字节码的最佳方法是什么,如果 [=25 仍然可行的话=] 9+.

The premain method is obviously not applicable here, because it is executed before main, which means it can't depend on something that is set up in main

这不是真的。代理不需要在代理加载时修改 class 字节码。它可能只是注册 ClassFileTransformer 并推迟字节码操作,直到稍后加载目标 class 。或者,代理可以简单地保存 Instrumentation 个实例,以便以后在任何方便的时候使用。

in the newer versions (9+), the dependencies needed to do that (tools.jar) don't seem to be present anymore

这也不完全正确。附加 API 存在于 JDK 的所有新版本中。由于 JDK 9 它不再需要 tools.jar,而是属于 jdk.attach 模块。

为了便于在运行时附加,您可以使用 byte-buddy-agent or a standalone jattach 实用程序。两者都适用于 JDK 8- 以及 JDK 9+.