Code implementation:
PackageCom.lky.proxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public classDynamicproxyImplementsInvocationhandler {PrivateObject obj;//the target object being called Publicdynamicproxy (Object obj) { This. obj =obj; } /*** @Title: Invoke@paramarg0@paramArg1 method of the target object being called@paramarg2 parameters of the target object method being called@return @throwsthrowable Parameters *@returnreturn type*/@Override PublicObject Invoke (Object arg0, Method arg1, object[] arg2)throwsthrowable {Object result=NULL; Dobefore (); Result=arg1.invoke (obj, arg2); Doafter (); returnresult; } //Factory mode generating dynamic dynamic agent Public StaticObject Proxyfactory (Object object) {Class<?extendsObject> CLS =Object.getclass (); returnProxy.newproxyinstance (Cls.getclassloader (), cls.getinterfaces (),NewDynamicproxy (object)); } Public voidDobefore () {System.out.println ("Initialize ..... "); } Public voidDoafter () {System.out.println ("Log processing ..... "); }}
Test code:
PackageCom.lky.proxy;Importorg.junit.Test; Public classTestproxy {@Test Public voidTest () {cat cat=NewCat (); Animal Animal=(Animal) dynamicproxy.proxyfactory (cat); Animal.eat (); System.out.println ("-------------------"); Animal.sleep (); System.out.println ("-------------------"); Car Car=NewCar (); Vehicle Vehicle=(Vehicle) dynamicproxy.proxyfactory (car); Vehicle.run (); System.out.println ("-------------------"); Vehicle.stop (); } }
Note:
- Abstract role (abstract class or interface), the real role (the real implementation of the business logic interface), the proxy role (itself does not implement the business logic interface, but call the real role to implement), where the interface and interface implementation is not enumerated, only the dynamic proxy generation
- A class to be able to handle dynamic proxies must implement the Invocationhandler interface
- The acquisition of a dynamic proxy requires the newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) method of the proxy to generate
- Invoke (Object Proxy, method, object[] args) method is called dynamically by the JVM at run time
Dynamic proxy Design Patterns for Java