One of the system classes of deep simulation Java Dynamic Agent implementation

Source: Internet
Author: User

The previous blog is the most basic implementation of the dynamic agent principle, because it fixed the interface, fixed the proxy method, and fixed the type of Agent ,
The next blog class will step into the depth introduction of the implementation of Java Dynamic Agent principle


****************************************************************************
First of all, to add a "Java Agent" knowledge, static proxy implementation includes two ways, one is aggregation, the other is inheritance.
Aggregation refers to the specific method of invoking its implementation class through an interface: for example, interface I, containing the method run (); Class A implements the interface I, of course
The method run () is also implemented; Class B can then invoke the run () method of a with the new interface I object, and implement the other operations before and after the run () method.
This implements the agent for the Run () method of a.
Inheritance, of course, is better understood, is to rewrite the run () method, thus implementing the Proxy
However, once the agent of many operations, the need to write classes are very complex, it is necessary to constantly write agent class, constantly update agent operations, so this has a dynamic
State agent.

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

This time, the class that implements any interface should be proxied.

1. Interface
public interface Moveable {
void Move ();
}

2. The object being proxied
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. Used to generate proxy objects
public class Proxy {
//Generate a new dynamic proxy class
public static Object newproxyinstance (Class intf) throws exception{//The interface is passed as a parameter, so that the class of any interface can be implemented, and not only implements the moveable interface
Dynamically compile the string to generate the proxy class
Implementation mode has the following hit: jdk6.0 complier API;  CGLib; Asm
String RT = "\ r \ n";
String src =
"Public class Tanktimeproxy implements" +intf.getname () + "{" +rt+//directly with intf, is to call the ToString method, before the string is added interface
Intf.getname () + "t;" +rt+

"Public Tanktimeproxy (" +intf.getname () + "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+
"}";

To compile
String fileName = "G:/src/tanktimeproxy.java";//store files separately, do not place the default path in the project, prevent conflicts of buffer related classes
File F = new file (fileName);
FileWriter FW = new FileWriter (f);
System.out.println (FileName);
Fw.write (SRC); Write content

Fw.flush ();
Fw.close ();

To compile
Get the compiler first
compiler is the Java compiler Javac
Get Compiler Object
Javacompiler compiler = Toolprovider.getsystemjavacompiler ();
System.out.println (Compiler.getclass (). GetName ());//Get class name
parameter meaning (compile diagnostics, Locale,charset)
Manage dynamically generated files
Standardjavafilemanager FileManager = Compiler.getstandardfilemanager (null,null,null);//Default value
Get multiple Java files based on parameters return Java file object
Iterable units = filemanager.getjavafileobjects (fileName);

The Compile Task object
Javacompiler.compilationtask task = Compiler.gettask (null,filemanager,null,null,null,units);
Task.call ();//Call
Filemanager.close ();

The above process obtained the Java File source code, compiled the Java file generated by the class file *******
Load into memory, generate new objects
Class.load (0 is a class file that loads a path path
URLClassLoader is to load the class file from the hard drive into

Introducing local files via URLs
url[] urls = new Url[]{new URL ("file:/" + "g:/src/")};//Specify where to generate the class file, and place it in the same directory as the Java file
To specify a path to find a class file
URLClassLoader URLClassLoader = new URLClassLoader (URLs);

Class C = Urlclassloader.loadclass ("Tanktimeproxy");

System.out.println (c);

Perform
C.newinstance (); is to call the empty constructor method

Get the construction method
Depending on the Java virtual machine, each construction method is also equivalent to an object
Constructor Constructor = C.getconstructor (intf);

Generating new objects
Moveable M = (moveable) constructor.newinstance (new Tank ()); New Tank () is the proxy object for the constructor method's argument

M.move ();

return m;
}
}


4. Test End
public class Client {
public static void Main (string[] args) throws Exception {

//Here to moveable interface as an example, because in the proxy in order to save trouble, or fixed generated moveable, and then slowly simplify, in fact, can be passed arbitrary interface
Moveable M = (moveable) proxy.newproxyinstance (Moveable.class);
M.move ();

}
}

5. Results

(1) Generated Java and class files

(2) Code for Java files

(3) Operation result

One of the system classes of deep simulation Java Dynamic Agent implementation

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.