There are many tools for processing Java bytecode, such as bcel and ASM. However, these operations must be handled directly with VM commands. If you do not want to know about VM commands, you can use
Javassist. Javassist is a subproject of JBoss. It has the advantages of being simple and fast. Directly Using Java encoding, without having to know about virtual machines
Command to dynamically change the class structure or dynamically generate classes.
The following is a simple example of how to dynamically inject code using Javassist.
Suppose there is Class A, as follows: Java code
- Public ClassA {
- Public VoidMethod (){
- For(IntI = 0; I <1000000; I ++ ){
- }
- System. Out. println ("Method1 ");
- }
- }
The test class B is as follows: Java code
- Public ClassB {
- Public Static VoidMain (string [] ARGs ){
- A A =NewA ();
- A. Method ();
- }
- }
Now I want to count the execution time of the method,
The default implementation is to modify the method: Java code
- Public VoidMethod (){
- LongStart = system. currenttimemillis ();
- For(IntI = 0; I <1000000; I ++ ){
- }
- System. Out. println ("Method1 ");
- LongEnd = system. currenttimemillis ();
- System. Out. println (end-Start );
- }
If a has many methods, the code for calculating the method execution time will increase accordingly. To reduce the workload, it is implemented by dynamically injecting code.
Modify the main method of B: Java code
- Public Static VoidMain (string [] ARGs)ThrowsException {
- // Used to obtain the bytecode class. It must be in the current classpath and use the full name
- Ctclass = classpool. getdefault (). Get ("org. esoft. ");
- // Method name to be modified
- String mname = "method ";
- Ctmethod mold = ctclass. getdeclaredmethod (mname );
- // Modify the original method name
- String nname = mname + "$ impl ";
- Mold. setname (nname );
- // Create a new method and copy the original method
- Ctmethod mnew = ctnewmethod. Copy (mold, mname, ctclass,Null);
- // Main injection code
- Stringbuffer body =NewStringbuffer ();
- Body. append ("{/nlong start = system. currenttimemillis ();/N ");
- // Call the original code, similar to method (); ($) indicates all parameters
- Body. append (nname + "($);/N ");
- Body. append ("system. Out. println (/" call to method"
- + Mname
- + "Took/" +/N (system. currenttimemillis ()-Start) +"
- + "/" Ms./");/N ");
- Body. append ("}");
- // Replace the New Method
- Mnew. setbody (body. tostring ());
- // Add a new method
- Ctclass. addmethod (mnew );
- // The class has been changed. You cannot use a A = new A (); because the same classloader cannot load the same class twice.
- A A = (a) ctclass. toclass (). newinstance ();
- A. Method ();
- }
This is just a simple application. Javassist also provides many functions for modifying the class structure. If you are interested, refer to the relevant documentation.
From: http://hi.baidu.com/winterhome/blog/item/f41314f4b2e073def2d38531.html