The first thing to understand is the concept:
**handler: Processor. Deal with business logic and things like that.
**proxy: Agent. Give me the agent, I help you manage things, I go to do what you should do! I'm a waiter in the limelight.
/* The original interface, will be delegated to the agent */
Public interface MyInterface {public void execute ();}
/* The original interface implements */public class Myinterfaceimpl implements MyInterface {@Overridepublic void execute () {System.out.println (" Execute () be called ");}}
To create a proxy:
(MyInterface) Proxy.newproxyinstance (
Myinterfaceimpl.getclass (). getClassLoader (),
Myinterfaceimpl.getclass (). Getinterfaces (),
handler);
Proxy.newproxyinstance (PARA1,PARA2,PARA3)
1.PARA1 is a class loader that is implemented by the proxy class (the original Interface) ClassLoader (some static resources are placed in it. class, etc., not detailed)
2.PARA2 all interfaces implemented by the proxy class
3.PARA3 (passed in the proxy class) processor
After this code is run, the agent generates, and all calls to the agent are forwarded to handler, which is the implementation class that is forwarded to the Invocationhandler interface.
(---All method calls to the dynamic proxy is forwarded InvocationHandler
to this implementation)
Import Java.lang.reflect.proxy;public class Client {public static void main (string[] args) {//My interface implementation The proxy object MyInterface Myinterfaceimpl = new Myinterfaceimpl ();//Processor Business proxy class Businesshandler handler = new Businesshandler ( MYINTERFACEIMPL);//Agent obtains an instance of the proxy class ($Proxy 0 extends proxy implements MyInterface). MyInterface Myinterfaceproxy = (myinterface) proxy.newproxyinstance (Myinterfaceimpl.getclass (). GetClassLoader (), Myinterfaceimpl.getclass (). Getinterfaces (), handler); Myinterfaceproxy.modify ();}}
Import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;/*invocationhandler Handler classes */public class Businesshandler implements Invocationhandler {Private Object object = Null;public Businesshandler (Object object) { This.object = object;} /** * * @param proxy is the agent, generally no use of * @param Method proxy methods, using the reflection mechanism, you can dynamically get all the information of the method. * @param args The parameters required by the method being called (not necessary) * **/@Overridepublic object Invoke (Object proxy, Method method, object[] args) throw s Throwable {System.out.println ("do something Before Method"); Object ret = Method.invoke (this.object, args); System.out.println ("Do something After Method"); return ret;}}
Reference Links:
Http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html (Reflection)
Http://hi.baidu.com/malecu/item/9e0edc115cb597a1feded5a0
Java Dynamic Agent (proxy, Invocationhandler)