Java Dynamic Agent Initial solution
Proxy mode: Simply speaking, it is a matter of another object to operate on behalf of. The simplest example, write an interface, a class to implement the method in this interface, but suddenly one day to add to the method such as logging, access permissions and other functions, then we can write another class to implement the method in the interface, and then add such as logging, access to the code, referring to the original class method to complete the encapsulation. However, there is a problem, that is, the number of classes in the system will increase, causing the system to run more memory (both the new class and the original class will consume memory), so Java provides a dynamic proxy mode for the interface. Why is called dynamic, because it uses the Java reflection mechanism, through the Reflection interface class object to encapsulate the generation of the new class object, and through the system provided by the Invocationhandler interface to increase the functionality of the original method of expansion.
For example: Proxy object class Newproxyinstance, which is used to create proxy objects.
public static Object newproxyinstance (ClassLoader loader,
Class<?>[] interfaces,
Invocationhandler h)
Throws IllegalArgumentException
In the source code:
Final Invocationhandler ih = h;
Final class<?>[] Intfs = Interfaces.clone ();//You can see that the interface is copied first
class<?> cl = GETPROXYCLASS0 (loader, intfs);//The interface class is then encapsulated with the ClassLoader to produce a new class object
Final constructor<?> cons = Cl.getconstructor (constructorparams);//construction method based on parameters
The parameter Constructorparams in the construction method is a Invocationhandler.class
private static final class<?>[] Constructorparams = {Invocationhandler.class};
Finally return Newinstance (cons, IH);
In other words, the proxy object is created by encapsulating the original interface and expanding a new interface, which is implemented in the new Interface Invoke ()
public object invoke (object proxy, Method method, object[] args)
Throws Throwable;
That is, you can add a new function code to this method, and then call the original method by means of the original class.
Object obj=method.invoke (test, args); test: The proxy class, args: Method parameter
In this way, when proxy calls Newproxyinstance to generate the surrogate object, invoking the method in the proxy class, it goes to the Invoke () method in the Invocationhandler interface implementation class to add new functionality and invoke the original method of the proxy class.
Java Dynamic Agent Initial solution