Java Dynamic Agent modified to proxy any interface

Source: Internet
Author: User

I. Overview

1. Target: Modify proxy to proxy any interface and any of its methods

2. Ideas:

(1) Proxy arbitrary interface: newproxyinstance (Class interfze) to pass the interface type as parameter to Proxy

(2) Proxy arbitrary method: Use Interfze.getmethods () to remove all methods, splicing the implementation of the method of the string

Second, the Code

1.movable.java

2.tank.java

3.proxy.java

4.client.java

1.movable.java

1  Package proxy; 2 3  Public Interface Movable {4      Public void move (); 5      Public void stop (); 6 }

2.tank.java

1  Packageproxy;2 3 ImportJava.util.Random;4 5  Public classTankImplementsMovable {6 7 @Override8      Public voidMove () {9System.out.println ("Tank moving ...");Ten         Try { OneThread.Sleep (NewRandom (). Nextint (2000)); A}Catch(interruptedexception e) { - e.printstacktrace (); -         } the     } -  - @Override -      Public voidStop () { +System.out.println ("Tank stopping ..."); -          +     } A  at}

3.proxy.java

1  Packageproxy;2 3 ImportJava.io.File;4 ImportJava.io.FileWriter;5 ImportJava.lang.reflect.Constructor;6 ImportJava.lang.reflect.Method;7 ImportJava.net.URL;8 ImportJava.net.URLClassLoader;9 Ten ImportJavax.tools.JavaCompiler; One ImportJavax.tools.JavaCompiler.CompilationTask; A ImportJavax.tools.StandardJavaFileManager; - ImportJavax.tools.ToolProvider; -  the  Public classProxy { -  -      Public StaticObject newproxyinstance (Class interfze)throwsException { -          +String RT = "\n\r"; -          +         //splicing The string "Implement Interface method" AString methodstr = ""; at          for(Method m:interfze.getmethods ()) { -              -             //Remove the modifier and return value type of the method -String [] parts = m.tostring (). Replace ("abstract", ""). Split ("\ \").); -String [] parts2 = Parts[0].split (""); -              inMethodstr + = -"@Override" + RT + toparts2[0]+ "" +parts2[1]+ "" +m.getname () + "() {" + RT + +"System.out.println (\" Time Proxy start...........\ ");" + RT + -"Long start = System.currenttimemillis ();" + RT + the"M." + m.getname () + "();" + RT + *"Long end = System.currenttimemillis ();" + RT + $"System.out.println (\" spend time: \ "+ (End-start));" + RT +Panax Notoginseng"System.out.println (\" Time Proxy end...........\ ");" + RT + -"}" ; the         } +          A          the         //the source of dynamic proxy files +String str = -"Package proxy;" + RT + $  $"Public class Tanktimeproxy implements" + interfze.getname () + "{" +rt+ -  -"Private" + interfze.getname () + "m;" + RT + the              -"Public tanktimeproxy (" + interfze.getname () + "m) {" + RT +Wuyi"THIS.M = m;" + RT + the"}" + RT + -  WuMethodstr + RT + -  About"}" ; $          -         //write the source code in the Java file. -File File =NewFile (System.getproperty ("User.dir") + "/src/proxy/tanktimeproxy.java"); -FileWriter FW =NewFileWriter (file); A fw.write (str); + Fw.flush (); the fw.close (); -          $         //Compile the source code, generate class, note that the compilation environment to be replaced by the JDK compiler, simple JRE no compiler, will be null pointer error theJavacompiler JC =Toolprovider.getsystemjavacompiler (); the          the         //file Steward theStandardjavafilemanager filemgr = Jc.getstandardfilemanager (NULL,NULL,NULL); -          in         //Compilation Unit theIterable units =filemgr.getjavafileobjects (file); the          About         //Compiling Tasks theCompilationtask t = jc.gettask (NULL, Filemgr,NULL,NULL,NULL, units); the          the         //compiling + T.call ();  - filemgr.close (); the         Bayi         //load the class into memory theurl[] URLs =NewUrl[] {NewURL ("file:/" +system.getproperty ("User.dir") + "/src/proxy/tanktimeproxy.class")}; theURLClassLoader UC =NewURLClassLoader (URLs); -Class C = Uc.loadclass ("Proxy. Tanktimeproxy "); -          the         //Build Instance the         //return c.newinstance ();//c.newinstance () will call the parameterless Construtor if the class does not have an constructor with no arguments theConstructor CTR =C.getconstructor (interfze); the         returnCtr.newinstance (NewTank ()); -     } the}

4.client.java

1  Packageproxy;2 3 Importjava.io.IOException;4 5 Importorg.junit.Test;6 7  Public classClient {8 9 @TestTen      Public voidTestproxy ()throwsexception{ One          AMovable m = (movable) proxy.newproxyinstance (movable.class); - M.move (); - m.stop (); the          -     } -}

Iii. Results of operation

Java Dynamic Agent modified to proxy any interface

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.