Simulate the underlying implementation principle of the dynamic proxy mechanism in java

Source: Internet
Author: User

Simulate the underlying implementation principle of the dynamic proxy mechanism in java

I learned the design mode visual screen of Jack Ma on the Internet, and made notes carefully during the process. Share some of my
The results help you learn more.

1. Interface
Public interface Moveable {
Void move ();
}

2. Proxy objects
Public class Tank implements Moveable {

@ Override
Public void move (){

System. out. println ("Tank Moving ...");
Try {
Thread. sleep (new Random (). nextInt (10000 ));
} Catch (InterruptedException e ){
E. printStackTrace ();
}

}

}

3. Test the main class

Public class Test {
Public static void main (String [] args) throws Exception {
String rt = "\ r \ n ";

// String code of the proxy class
String src =
"Public class TankTimeProxy implements Moveable {" + rt +
"Moveable t;" + rt +

"Public TankTimeProxy (Moveable t) {" + rt +
"This. t = t;" + rt +
"}" + Rt +

"@ Override" + rt +
"Public void move () {" + rt +
"Long start = System. currentTimeMillis ();" + rt +
"System. out. println (\" start time is \ "+ start);" + rt +
"T. move ();" + rt +
"Long end = System. currentTimeMillis ();" + rt +
"System. out. println (\" end time is \ "+ end);" + rt +
"System. out. println (\" time is \ "+ (end-start);" + rt +
"}" + Rt +
"}";

// Write the string to the java file ********************************* **************************************** *******
String fileName = System. getProperty ("user. dir") + "/src/TankTimeProxy. java"; // place it under (root directory + file name)
File f = new File (fileName );
FileWriter fw = new FileWriter (f );
// Write content
Fw. write (src );
Fw. flush ();
Fw. close ();

// Compile ************************************ **************************************** ****************
// Obtain the compiler first
// Compiler is a java compiler, that is, javac.
// Obtain the compiler object
JavaCompiler compiler = ToolProvider. getSystemJavaCompiler ();

// Parameter meaning (compilation diagnosis, locale, charset)
// Manage the StandardJavaFileManager object of dynamically generated files
StandardJavaFileManager fileManager = compiler. getStandardFileManager (null, null, null); // Default Value

// Obtain multiple java files based on parameters and return the java file object set
Iterable units = fileManager. getJavaFileObjects (fileName );

// Compile the task object
JavaCompiler. CompilationTask task = compiler. getTask (null, fileManager, null, units );
Task. call (); // call
FileManager. close ();

// ************* The above process obtains the java file source code, compile the java file and generate the corresponding class file ****************

// **************** The following process is to load the class file to the memory, generate a new object *****************************
// Class. load () is the class file that loads the path
// URLClassLoader is used to load the class file in the hard disk

// Introduce local files through URLs
URL [] urls = new URL [] {new URL ("file:/" + System. getProperty ("user. dir ") +"/out/production/proxy ")}; // access the local class file. Here I use IntellijIDEA, the default class file directory is in/out/production /.


// Find the class file in the specified path
URLClassLoader urlClassLoader = new URLClassLoader (urls );

Class c = urlClassLoader. loadClass ("TankTimeProxy ");

System. out. println (c );

// Execute
// C. newInstance (); is the empty constructor.

// Obtain the constructor
// Based on the Java Virtual Machine, each constructor is equivalent to an object.
Constructor constructor = c. getConstructor (Moveable. class );

// Generate a new object
Moveable m = (Moveable) constructor. newInstance (new Tank (); // new Tank () is the parameter of the constructor.

M. move ();

}
}

 

4. Execution 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.