简体   繁体   English

如何为已经运行的实例更改Java类的代码?

[英]How can I change the code for a Java class for an already running instance?

I wish to dynamically add and remove instrumentation code to a Java class file several times without restarting the Java JVM. 我希望多次动态地向Java类文件添加和删除检测代码,而无需重新启动Java JVM。 Is this possible? 这可能吗?

I suggest you look at the java.lang.instrument package , especially the ClassFileTransformer . 我建议你看看java.lang.instrument ,尤其是ClassFileTransformer

Here is a good article: Instrumentation: Modify Applications with Java 5 Class File Transformations 这是一篇很好的文章: Instrumentation:使用Java 5类文件转换修改应用程序

For actual bytecode generation, I suggest you have a look at libraries such as BCEL or ASM . 对于实际的字节码生成,我建议您查看BCELASM等库。

The JRebel framework may also interest you. JRebel框架也可能对您感兴趣。 It can change implementation of method bodies, add / remove methods and constructors, add/remove fields, add/remove classes etc, all in runtime. 它可以在运行时更改方法体的实现,添加/删除方法和构造函数,添加/删除字段,添加/删除类等。

您可以使用辅助类(策略设计模式),它可以在运行时交换为另一个。

You can use Jrebel for hot deployment. 您可以使用Jrebel进行热部署。 It will allow you to change the code without server restart. 它允许您在不重启服务器的情况下更改代码。

You also might want to look at ByteMan from JBoss. 你也许想看看JBoss的ByteMan It uses the same Java agent mechanism and specifically supports installing and uninstalling your modification scripts, see the tutorial . 它使用相同的Java代理机制,特别支持安装和卸载修改脚本,请参阅教程 What follows is an abridged version of the tutorial: 以下是教程的简略版本:

For example lets say we have some running Java Process: 例如,假设我们有一些正在运行的Java进程:

$ jps
15295 Jps
4884 main

We can then install ByteMan into the running process: 然后我们可以将ByteMan安装到正在运行的进程中:

$ bminstall.sh 4884

You could then create a ByteMan script: 然后,您可以创建一个ByteMan脚本:

$ youreditor thread.btm
RULE trace thread start
CLASS java.lang.Thread
METHOD start()
IF true
DO traceln("*** start for thread: "+ $0.getName())
ENDRULE

You can then install a ByeMan script with: 然后,您可以使用以下命令安装ByeMan脚本:

$ bmsubmit.sh -l thread.btm

To remove: 去除:

$ bmsubmit.sh -u thread.btm

To list what is currently running just issue it without any arguments: 要列出当前正在运行的内容,只需发出它而不带任何参数:

$ bmsubmit.sh

If you are running on windows replace the .sh in each command with .bat. 如果您在Windows上运行,请使用.bat替换每个命令中的.sh。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM