Java instrument Modifying bytecode implements AOP functionality

Source: Internet
Author: User

Agent Engineering 2 classes:

 Public classmyagent {/*** This method runs before the main method, runs in the same JVM as the main method * and is loaded by the same system ClassLoader * Unified security Policy and context management */     Public Static voidPremain (String agentops, Instrumentation inst) {System.out.println ("=========premain Method Execution ========");        System.out.println (Agentops); //Add transformerInst.addtransformer (NewMytransformer ()); }    /*** If the Premain (string agentops, Instrumentation Inst) * Does not exist, Premain (string agentops) is executed*/     Public Static voidPremain (String agentops) {System.out.println ("=========premain Method Execution 2========");    System.out.println (Agentops); }}
 Public classMytransformerImplementsClassfiletransformer {Final StaticString prefix = "\nlong startTime = System.currenttimemillis (); \ n"; Final StaticString postfix = "\nlong endTime = System.currenttimemillis (); \ n"; //list of methods to be processed    Final Staticmap<string, list<string>> methodmap =NewHashmap<string, list<string>>();  PublicMytransformer () {Add ("Com.hwtest.demo.MyProgram.sayHello"); Add ("Com.hwtest.demo.MyProgram.sayHello2"); }    Private voidAdd (String methodstring) {string ClassName= methodstring.substring (0, Methodstring.lastindexof ("."))); String MethodName= Methodstring.substring (Methodstring.lastindexof (".") + 1); List<String> list =Methodmap.get (className); if(List = =NULL) {List=NewArraylist<string>();        Methodmap.put (ClassName, list);    } list.add (MethodName); } @Override Public byte[] Transform (ClassLoader loader, String className, class<?>classbeingredefined, Protectiondomain Protectiondomain,byte[] classfilebuffer)throwsillegalclassformatexception {className= Classname.replace ("/", ".")); if(Methodmap.containskey (ClassName)) {//determine if the package path of the loaded class is a class that needs to be monitoredCtclass Ctclass =NULL; Try{Ctclass= Classpool.getdefault (). get (ClassName);//use full name to get bytecode class < use javassist>                 for(String MethodName:methodMap.get (ClassName)) {string Outputstr= "\nsystem.out.println" (\ "This method" +MethodName+ "Cost:\" + (endtime-starttime) +\ "ms.\"); "; Ctmethod Ctmethod= Ctclass.getdeclaredmethod (MethodName);//get This method instanceString newmethodname = methodName + "$old";//a new definition of a method called Sayhello$old, for exampleCtmethod.setname (Newmethodname);//Modify the original method name//Create a new method, copy the original method, the name is the original nameCtmethod Newmethod = ctnewmethod.copy (Ctmethod, MethodName, Ctclass,NULL); //building a new method bodyStringBuilder Bodystr =NewStringBuilder (); Bodystr.append ("{");                    Bodystr.append (prefix); Bodystr.append (Newmethodname+ "($$); \ n");//call the original code, similar to Method ();($$) to represent all parametersbodystr.append (postfix);                    Bodystr.append (OUTPUTSTR); Bodystr.append ("}"); Newmethod.setbody (Bodystr.tostring ());//Replace New MethodCtclass.addmethod (Newmethod);//Add new methods                }                returnCtclass.tobytecode (); } Catch(Exception e) {System.out.println (E.getmessage ());            E.printstacktrace (); }        }        return NULL; }}

Original project:

 Public classMyProgram { Public Static voidMain (string[] args) {SayHello (); SayHello2 ("Hello world222222222"); }         Public Static voidSayHello () {Try{Thread.Sleep (2000); System.out.println ("Hello world!!"); } Catch(interruptedexception e) {e.printstacktrace (); }    }     Public Static voidSayHello2 (String hello) {Try{Thread.Sleep (1000);        System.out.println (hello); } Catch(interruptedexception e) {e.printstacktrace (); }    }}

The agent project hit jar package is configured to:

manifest-version:1.0premain-Class:com.hwtest.MyAgentCantrueBoot- Class-path:javassist.jar

CMD execution command

Java-javaagent:myagent.jar  -jar Myprogram.jar=========premain method execution ========nullHello World!!  This method SayHello Cost:2000ms.hello world222222222  This method SayHello2 cost:1000ms.

Address record:

(1) using Classfiletransformer to realize aop:http://xj84.iteye.com/blog/1221105

(2) Java implements AOP functionality by modifying the bytecode of a class: Http://www.360doc.com/content/07/0518/11/25392_506401.shtml

(3) java.lang.instrument Dynamic Modification Replacement Class code: http://zctya.blog.163.com/blog/static/1209178201131944127774/

Java instrument Modifying bytecode implements AOP functionality

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.