On-line self-taught the next Java agent, put out the code to make a note and summary
First, the purpose of using the agent
1. Route method calls to the remote server
2. Associating user interface events and actions during program operation
3, for debugging, tracking method calls and so on
Ii. the classes and interfaces required to implement the agent include:
1. proxy class used to generate Agent class
2, the proxy class needs to implement the interface, here with the moveable
3. Call Processor Interface Invocationhandler
4, the specific agent of the class, here is tank, it implements the Mobeable interface
5. Implement the wrapper class that invokes the processor interface, here is Timehandler
Third, the proxy class is dynamically generated in the proxy class, and must be implemented by the proxy class interface, the proxy class has the method:
1, specify the interface of all the methods required, here is moveable
2. All methods in the object class, for example: toString (), Equals (), because object is a superclass of all classes
In the following example, the proxy logic to be implemented here is that the tank class records the current time before and after each call to the move () method
The first is the test class
Package Proxy;import Java.io.ioexception;import Java.lang.reflect.invocationtargetexception;public class ProxyTest { public static void Main (string[] args) throws SecurityException, IllegalArgumentException, IOException, ClassNotFoundException, Nosuchmethodexception, Instantiationexception, Illegalaccessexception, invocationtargetexception {Tank t=new Tank (); Invocationhandler h=new Timehandler (t); Moveable m= (moveable) proxy.newproxyinstance (moveable.class,h); M.move (); }}
interface of the class being proxied
Package Proxy;public interface Moveable {public void move ();}
The class being proxied
Package Proxy;public class Tank implements moveable{@Override public void Move () {thread t=new thread (); T.start (); try {t.sleep (2000); } catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Moving ..."); }
Time-processing wrapper, the constructor needs to pass the object being proxied
Package Proxy;import Java.lang.reflect.method;import Java.util.date;public class Timehandler implements Invocationhandler {Object Target;public Timehandler (object target) {super (); this.target=target;} @Overridepublic void Invoke (Object o,method m) {System.out.println ("Start time:" +new Date (). toLocaleString ()); try{ M.invoke (target);} catch (Exception e) {e.printstacktrace ();} System.out.println ("End time:" +new Date (). toLocaleString ());}}
The most important proxy
Package Proxy;import Java.io.*;import Java.lang.reflect.*;import java.net.*;import javax.tools.javacompiler;import Javax.tools.javacompiler.compilationtask;import Javax.tools.; public class Proxy {public static Object Newproxyinstance (class Intrfc,invocationhandler H) throws IOException, CLASSNOTF Oundexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, InstantiationException, Illegalaccessexception, invocationtargetexception {String mthstr= "";//To save a detailed implementation of all methods inherited from Intrfc method[] methods= Intrfc.getmethods ();//used to save Intrfc all method name for (method m:methods) {mthstr+= ' @Override "+" + "public void" +m.getname () + "() {"+" try{"+" Method md= "+intrfc.getname () +". Class.getmethod (\ "" +m.getname () + "\"); " + "H.invoke (THIS,MD);" + "}catch (Exception e) {" + "}" + "}";} String str = "Import Java.lang.reflect.Method;" + "public class Myproxy implements" + intrfc.getname () + "{" + "proxy. Invocationhandler h; " + "Public myproxy" (proxy. Invocationhandler h) {"+" THIS.H=H; " + "}" +mthstr+ "}"; String Filename = "D:/workspaces/eclipse/designpattern/src//myproxy.java"; File F = new file (fileName); FileWriter FW = new FileWriter (f); Fw.write (str); Fw.flush (); Fw.close ();//compilejavacompiler compiler= Toolprovider.getsystemjavacompiler (); Standardjavafilemanager Filemgr=compiler.getstandardfilemanager (null, NULL, NULL); Iterable units= Filemgr.getjavafileobjects (FileName); Compilationtask task=compiler.gettask (null, filemgr, null,null,null,units); Task.call (); Filemgr.close ();// Load enters memory url[] urls = new url[] {new URL ("file:/" + "d:/workspaces/eclipse/designpattern/src/")}; URLClassLoader ul = new URLClassLoader (URLs); Class C=ul.loadclass ("myproxy");//The object created by the class instance must contain a default constructor, and the//timepproxy class does not contain a default constructor, so it can only be passed through/ An instance of constructor to create an object constructor Ctr=c.getconstructor (invocationhandler.class); object M=ctr.newinstance (h); return m ;}}About the core part of the proxy class implementation
1, the proxy class contains only one instance of the calling processor Invocationhandler H;
2, the proxy class implements all the methods of the interface implemented by the proxy class, and gives the implementation details to the calling processor H.invoke (THIS,MD);
3. Get the class object of proxy class by compiling, class loader and other techniques
4. Assign a value to the proxy class and construct the proxy object by passing in the call Processor object through Proxy.newproxyinstance ()
5. Return the created proxy object to the customer
Java Agent Summary