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

I want to dynamically add and remove toolkit code to a Java class file several times without restarting the Java JVM. Is it possible?

+4
source share
4 answers

I suggest you look at the java.lang.instrument package , especially the ClassFileTransformer .

Here is a good article: Instrumentation: Modify Applications Using Java 5 Class File Conversions

For actual bytecode generation, I suggest you look at libraries like BCEL or ASM .

The JRebel structure may also interest you. It can change the implementation of methods, add / remove methods and constructors, add / remove fields, add / remove classes, etc. At runtime.

+7
source

You can use a helper class (strategy development pattern) that can be replaced by another at runtime.

+2
source

You can use Jrebel for quick deployment. This will allow you to change the code without rebooting the server.

+1
source

You can also watch ByteMan from JBoss. It uses the same Java agent mechanism and, in particular, supports the installation and removal of modification scripts, see the tutorial . The following is an abridged version of the tutorial:

For example, let's say we have several running Java processes:

 $ jps 15295 Jps 4884 main 

Then we can install ByteMan in the current process:

 $ bminstall.sh 4884 

Then you can create a ByteMan script:

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

Then you can install the ByeMan script with:

 $ bmsubmit.sh -l thread.btm 

To delete:

 $ bmsubmit.sh -u thread.btm 

To list what is currently being executed, simply release it without any arguments:

 $ bmsubmit.sh 

If you are running Windows, replace .sh in each command with .bat.

0
source

Source: https://habr.com/ru/post/1337465/


All Articles