I wish to dynamically add and remove instrumentation cod开发者_运维百科e to a Java class file several times without restarting the Java JVM. Is this possible?
I suggest you look at the java.lang.instrument
package, especially the ClassFileTransformer
.
Here is a good article: Instrumentation: Modify Applications with Java 5 Class File Transformations
For actual bytecode generation, I suggest you have a look at libraries such as BCEL or ASM.
The JRebel framework may also interest you. It can change implementation of method bodies, add / remove methods and constructors, add/remove fields, add/remove classes etc, all in runtime.
You could use a helper class (Strategy Design Pattern) which may be swapped for another one at run-time.
You can use Jrebel for hot deployment. It will allow you to change the code without server restart.
You also might want to look at ByteMan from JBoss. It uses the same Java agent mechanism and specifically supports installing and uninstalling your modification scripts, see the tutorial. What follows is an abridged version of the tutorial:
For example lets say we have some running Java Process:
$ jps
15295 Jps
4884 main
We can then install ByteMan into the running process:
$ bminstall.sh 4884
You could then 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
You can then install a ByeMan script with:
$ 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.
精彩评论