For the dynamic agent of the JDK, Konghao says the way to learn is to write it down.
First, write a topic interface class that represents a topic to complete.
Package Com.liwei.dynaproxy; /** @author*/Publicinterface Subject { publicvoid miai ();}
Write an implementation class that implements this interface. Of course, this implementation class is the object we want to proxy.
In order to distinguish between objects of different classes, we have added a name attribute to the person class, and the name attribute value "injected" through the constructor, this is a difficult place for beginners to understand, in fact, write a few more times will understand.
PackageCom.liwei.dynaproxy;/*** The object being represented * *@authorAdministrator **/ Public classPersonImplementsSubject {PrivateString name; PublicPerson (String name) {Super(); This. Name =name; } Public voidMiai () {System.out.println (name+ "Being in a blind date ... "); }}
Next, write our dynamic proxy class.
Note: The dynamic proxy class implements the Invocationhandler interface of the JDK to implement the Invoke method.
Where the member variable object target represents the object being proxied. In the same way, it is injected through the constructor of the dynamic proxy class.
Emphasis: The 1th parameter of the Invoke method is not used by object proxy.
PackageCom.liwei.dynaproxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;/*** Dynamic proxy class, this is a processor * *@authorAdministrator **/ Public classDynaproxyImplementsInvocationhandler {PrivateObject Target;//The object being proxied PublicDynaproxy (Object target) {Super(); This. target =Target; } Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {Object Object=NULL; System.out.println ("Pre-notification ... "); Object=Method.invoke (target, args); System.out.println ("Return notification ... "); returnobject; } }
Finally, we write a test class.
PackageCom.liwei.dynaproxy;ImportJava.lang.reflect.Proxy; Public classTest { Public Static voidMain (string[] args) {person P=NewPerson ("Peng Liyuan"); Dynaproxy Dynaproxy=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. //dynamically generated proxy object (class loader, proxied interface, Invocationhandler)Subject s=(Subject) proxy.newproxyinstance (P.getclass (). getClassLoader (), P.getclass (). Getinterfaces (), Dynaproxy ); S.miai (); }}
Source code: Dynamic Proxy source code for JDK. rar
Dynamic proxy for Design patterns (JDK dynamic proxy implementation in Java)