One of the classes that deeply simulate the java Dynamic proxy implementation mechanism, java Dynamic

Source: Internet
Author: User

One of the classes that deeply simulate the java Dynamic proxy implementation mechanism, java Dynamic

The previous blog was the most basic implementation of the dynamic proxy principle, because it fixed the interface, fixed the proxy method, and fixed the proxy type,
The following blog series will gradually introduce java's dynamic proxy implementation principles.


**************************************** ************************************
First, I would like to add some knowledge about "java proxy". The implementation of static proxy includes two methods: Aggregation and inheritance.
Aggregation refers to calling the method of its implementation class through an interface: for example, interface I, containing the method run (); Class A implements interface I, of course
The run () method is also implemented. Class B can call the run () method of A through the object of A new interface I, and perform other operations before and after the run () method,
In this way, the proxy for the run () method of A is implemented;
Inheritance, of course, is to rewrite the run () method to implement proxy
However, once many proxy operations are performed and the classes to be written are complex, you need to constantly write proxy classes and update proxy operations.
Status proxy.

**************************************** *************************************

This time, proxy is required for classes that implement any interface.

1. Interface

public interface Moveable {    void move();}

  



2. Proxy objects

 1 public class Tank implements Moveable { 2  3     @Override 4     public void move() { 5          6         System.out.println("Tank Moving..."); 7         try { 8             Thread.sleep(new Random().nextInt(10000)); 9         } catch (InterruptedException e) {10             e.printStackTrace();11         }12         13     }14     15 }

 


3. Used to generate proxy objects

1 public class Proxy {2 // generate a new dynamic Proxy Class 3 public static Object newProxyInstance (class intf) throws Exception {// pass the interface as a parameter, in this way, the proxy can implement any interface class, not only the Moveable interface 4 // dynamically compile the string, but also generate the proxy class 5 // The following implementation methods are hit: jdk6.0 complier API; CGLib; ASM 6 String rt = "\ r \ n"; 7 String src = 8 "public class TankTimeProxy implements" + intf. getName () + "{" + rt + // use intf directly to call the toString method. The string interface 9 intf will be added before. getName () + "t;" + rt + 10 11 "public TankTimeProxy (" + intf. getName () + "t) {" + rt + 12 "this. t = t; "+ rt + 13"} "+ rt + 14 15" @ Override "+ rt + 16" public void move () {"+ rt + 17" long start = System. currentTimeMillis (); "+ rt + 18" System. out. println (\ "start time is \" + start); "+ rt + 19" t. move (); "+ rt + 20" long end = System. currentTimeMillis (); "+ rt + 21" System. out. println (\ "end time is \" + end); "+ rt + 22" System. out. println (\ "time is \" + (end-start); "+ rt + 23"} "+ rt + 24 "}"; 25 26 // compile 27 String fileName = "g:/src/TankTimeProxy. java "; // store files separately, not in the default path of the project, to prevent conflicts between buffer-related classes 28 File f = new File (fileName ); 29 FileWriter fw = new FileWriter (f); 30 // System. out. println (fileName); 31 fw. write (src); // write content 32 33 fw. flush (); 34 fw. close (); 35 36 // compile 37 // obtain the compiler 38 // compiler is the java compiler javac39 // obtain the compiler object 40 JavaCompiler compiler = ToolProvider. getSystemJavaCompiler (); 41 // System. out. println (compiler. getClass (). getName (); // get the class name 42 // parameter meaning (compilation diagnosis, locale, charset) 43 // manage dynamically generated files 44 StandardJavaFileManager fileManager = compiler. getStandardFileManager (null, null, null); // The default value is 45 // obtain multiple java files based on parameters and return the java file object 46 Iterable units = fileManager. getJavaFileObjects (fileName); 47 48 // "compile task" Object 49 JavaCompiler. compilationTask task = compiler. getTask (null, fileManager, null, units); 50 task. call (); // call 51 fileManager. close (); 52 53 // ************* the java file source code is obtained in the above process, compile and generate the class file ******** 54 // load it to the memory and generate a new object 55 // Class. load (0 is the class file that loads the path 56 // URLClassLoader is to load the class file in the hard disk into 57 58 // introduce the local file via Url 59 URL [] urls = new URL [] {new URL ("file: /"+" g:/src/")}; // specifies the location where the class file is generated, place the file in the same directory as the java file 60 // find the class file 61 URLClassLoader urlClassLoader = new URLClassLoader (urls); 62 63 Class c = urlClassLoader in the specified path. loadClass ("TankTimeProxy"); 64 65 System. out. println (c); 66 67 // execute 68 // c. newInstance (); is to call the empty Constructor 69 70 // obtain the constructor 71 // according to the Java Virtual Machine, each Constructor is equivalent to an object 72 constructor Constructor = c. getConstructor (intf); 73 74 // generate new object 75 Moveable m = (Moveable) constructor. newInstance (new Tank (); // new Tank () is the constructor object 76 77 m. move (); 78 79 return m; 80} 81}

 




4. Test end

1 public class Client {2 public static void main (String [] args) throws Exception {3 4 // here, we use the Moveable interface as an example, because it saves trouble in Proxy, the fixed generation of Moveable will be simplified later. In fact, 5 Moveable m = (Moveable) Proxy of any interface can be passed. newProxyInstance (Moveable. class); 6 m. move (); 7 8} 9}

 



5. Results

(1) generated java and class files

(2) java File Code

(3) running result

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.