Java Dynamic Agent:
Java Dynamic proxy class is located under the Java.lang.reflect package, the general mainly involves two classes: 1.Interface Invocationhandler
Only one method is defined in this interface:object Invoke (Object Proxy,method method,object[] args)
The first parameter, obj, is typically a proxy class, method is a proxy, as in the previous example request (), args is an array of arguments in the method , no parameter is null
This abstract method is implemented dynamically in the proxy class.
2.Proxy
Protected Proxy (Invocationhandler h): constructor, used to assign values to internal invocation handler.
Static class<?> Getproxyclass (ClassLoader loader, class<?> .... Interfaces): loader is a class loader, Interfaces is an array of all the interfaces owned by the real class.
Static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h):
Returns an instance of the proxy class that can be used as a proxy class (a method declared in the subject interface that can be used by the proxy class).
Example 1:
Define an interface
/**/Publicinterface Subject {publicvoid request (); }
Define real-world role classes to implement interfaces
/**/Publicclassimplements subject{ @Override publicvoid request () { System.out.println ("from real subject");} }
Define the dynamic proxy class, implement the Invocationhandler interface, override the Invoke method
/** Dynamic proxy class, implement Invocationhandler interface, override Invoke method*/ Public classDynamicsubjectImplementsInvocationhandler {//reference to the object of the real class PrivateObject Sub; Publicdynamicsubject (Object obj) { This. Sub =obj; }
@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Before calling" +method); //invoking a method by reflectionMethod.invoke (sub, args); System.out.println ("After calling" +method); return NULL; }}
Test
Public classClient { Public Static voidMain (string[] args) {//Real class ObjectsRealsubject Realsubject =NewRealsubject (); //getting types from dynamic class objectsInvocationhandler handle =NewDynamicsubject (Realsubject); Class<?> ClassType =Handle.getclass (); //build Agent//dynamically generates a class that implements the specified interface to generate the object of the class into an interface type handle is an object of the dynamic proxy classSubject Subject =(Subject) proxy.newproxyinstance (Classtype.getclassloader (), Realsubject.getclass (). Getinterfaces (), H Andle); Subject.request (); System.out.println (Subject.getclass ()); }}
In this way, the Proxied object (Realsubject) can be dynamically changed at runtime, the interface that needs to be controlled (subject interface) can be changed at runtime, the control mode (Dynamicsubject Class) can also be changed dynamically, thus realizing a very flexible dynamic agent relationship.
Java Proxy mode two: Dynamic agent