1 import Java.lang.reflect.InvocationHandler;2 import Java.lang.reflect.Method;3 import Java.lang.reflect.Proxy;4 5 //The use of dynamic agent, the key to realize reflection is dynamic language6 InterfaceSubject {7 voidaction ();8 }9 Ten //by proxy class One classRealsubject implements Subject { A Public voidaction () { -System. out. println ("I am a proxy class, remember to execute me Oh! ?"); - } the } - - classMyinvocationhandler implements Invocationhandler { -Object obj;//declaration of an object that implements an interface's proxy class + - //① instantiation of a Proxied object ② returns an object of a proxy class + Publicobject Blind (object obj) { A This. obj =obj; at returnproxy.newproxyinstance (Obj.getclass (). getClassLoader (), obj -. GetClass (). Getinterfaces (), This); - } - //When a call to an overridden method is initiated through an object of the proxy class, it is converted to a call to the following Invoke method - @Override - Publicobject Invoke (Object proxy, Method method, object[] args) in throws Throwable { - //The return value of method methods is ReturnVal toObject ReturnVal =method.invoke (obj, args); + returnReturnVal; - } the * } $ Panax Notoginseng Public classTestproxy { - Public Static voidMain (string[] args) { the + //1. Object of the class being proxied ARealsubject real =NewRealsubject (); the //2. Create an object with a class that implements the Invacationhandler interface +Myinvocationhandler handler =NewMyinvocationhandler (); - //3. Call the Blind () method to dynamically return an object that implements the proxy class of the interface subject that the real class implements. $Object obj =Handler.blind (real); $Subject sub = (Subject) obj;//at this point the sub is the object of the proxy class - -Sub.action ();//go to the call of the Invoke () method on the implementation class of the Invacationhandler interface the - //One more exampleWuyiNikeclothfactory Nike =Newnikeclothfactory (); theClothfactory Proxycloth = (clothfactory) handler.blind (Nike);//Proxycloth is the object of the proxy class - Proxycloth.productcloth (); Wu - About $ } -}
Java Learning--The dynamic proxy mode of reflection