Dynamic agent is one of Gof 23 design patterns, database connection and transaction management, the method interception of AOP in spring, and the mock objects used in unit test are all used in dynamic proxy.
The Java Dynamic Agent can be implemented by using the class java.lang.reflect.Proxy of the JDK.
Create a dynamic proxy by using the Proxy.newproxyinstance () method.
The Newproxyinstance () method has three parameters:
1, ClassLoader
2. Interfaces that require agents
3, the implementation of Invocationhandler interface
Invocationhandler handler = new Myinvocationhandler (); MyInterface proxy = (myinterface) proxy.newproxyinstance ( MyInterface.class.getClassLoader (), new class[] { Myinterface.class}, handler);
Let's take a look at the definition of the Invocationhandler interface
Public interface invocationhandler{ object Invoke (Object proxy, Method method, object[] args) throws Throwable;}
All of the method calls to the dynamic proxy object proxy go to the implementation class of the Invocationhandler interface.
The Invocationhandler interface has only one invoke method, the proxy parameter in the Invoke method is the dynamic proxy object, and the method object is the methods in the proxy interface, and the args parameter is the method parameter.
Dynamic agent of Java