Use Javassist to dynamically inject code

Source: Internet
Author: User
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
  1. Public ClassA {
  2. Public VoidMethod (){
  3. For(IntI = 0; I <1000000; I ++ ){
  4. }
  5. System. Out. println ("Method1 ");
  6. }
  7. }

The test class B is as follows: Java code

  1. Public ClassB {
  2. Public Static VoidMain (string [] ARGs ){
  3. A A =NewA ();
  4. A. Method ();
  5. }
  6. }

Now I want to count the execution time of the method,
The default implementation is to modify the method: Java code

  1. Public VoidMethod (){
  2. LongStart = system. currenttimemillis ();
  3. For(IntI = 0; I <1000000; I ++ ){
  4. }
  5. System. Out. println ("Method1 ");
  6. LongEnd = system. currenttimemillis ();
  7. System. Out. println (end-Start );
  8. }

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

  1. Public Static VoidMain (string [] ARGs)ThrowsException {
  2. // Used to obtain the bytecode class. It must be in the current classpath and use the full name
  3. Ctclass = classpool. getdefault (). Get ("org. esoft. ");
  4. // Method name to be modified
  5. String mname = "method ";
  6. Ctmethod mold = ctclass. getdeclaredmethod (mname );
  7. // Modify the original method name
  8. String nname = mname + "$ impl ";
  9. Mold. setname (nname );
  10. // Create a new method and copy the original method
  11. Ctmethod mnew = ctnewmethod. Copy (mold, mname, ctclass,Null);
  12. // Main injection code
  13. Stringbuffer body =NewStringbuffer ();
  14. Body. append ("{/nlong start = system. currenttimemillis ();/N ");
  15. // Call the original code, similar to method (); ($) indicates all parameters
  16. Body. append (nname + "($);/N ");
  17. Body. append ("system. Out. println (/" call to method"
  18. + Mname
  19. + "Took/" +/N (system. currenttimemillis ()-Start) +"
  20. + "/" Ms./");/N ");
  21. Body. append ("}");
  22. // Replace the New Method
  23. Mnew. setbody (body. tostring ());
  24. // Add a new method
  25. Ctclass. addmethod (mnew );
  26. // The class has been changed. You cannot use a A = new A (); because the same classloader cannot load the same class twice.
  27. A A = (a) ctclass. toclass (). newinstance ();
  28. A. Method ();
  29. }

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.