1 PackageCom.gh.dynaproxy;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Method;5 /**6 * Dynamic proxy class7 * @authorGanhang8 *9 */Ten Public classDynaproxyImplementsinvocationhandler{ One PrivateObject ob;//The object being proxied A Publicdynaproxy (Object ob) { - This. ob=ob; - } the Private voidbefore () { -System.out.println ("Find objects for Proxy objects: "); - } - Private voidAfter () { +System.out.println ("Blind Date completed. "); - } + A @Override at Publicobject Invoke (Object proxy, Method method, object[] args) - throwsThrowable { -Object obj=NULL; - before (); -Obj=method.invoke (ob, args);//actually calling the business method - After (); in returnobj; - } to}
1 PackageCom.gh.dynaproxy;2 /**3 * by proxy class4 * @authorGanhang5 *6 */7 Public classPersonImplementssubject{8 PrivateString name;9 PublicPerson (String name) {Ten This. name=name; One } A @Override - Public voidMiai () { -System.out.println (name+ "is in a blind date ..."); the } - -}
1 PackageCom.gh.dynaproxy;2 /**3 * The subject interface to be proxied4 * @authorGanhang5 *6 */7 Public InterfaceSubject {8 9 Public voidMiai ();Ten One}
1 PackageCom.gh.dynaproxy;2 3 ImportJava.lang.reflect.Proxy;4 /**5 * Dynamic Agent6 * @authorGanhang7 *8 */9 Public classTest {Ten Public Static voidMain (string[] args) { OnePerson p=NewPerson ("small white"); ADynaproxy dp=NewDynaproxy (p); - //Proxy provides a static method for creating dynamic proxy classes and instances, or a superclass of all dynamic proxy classes created by these methods - //Newproxyinstance (class loader that defines the proxy class, list of interfaces to be implemented by the proxy class, Invocationhandler interface) the //returns a proxy class instance for the specified interface that can assign a method call to the specified invocation handler. It is defined by the specified class loader and implements the specified interface -Subject s=(Subject) proxy.newproxyinstance (P.getclass (). getClassLoader (), P.getclass (). Getinterfaces (), DP); - S.miai (); - } +}
Dynamic proxy mode of Java learning