Agent: Should have done their own things, but invited others to do, the person invited is the proxy object.
Example: Spring home to buy tickets for people
Dynamic Agent:
The object that is generated during the program's operation
And in the process of running the object is actually the reflection we just reflected the content, so, dynamic agent is actually through reflection to generate a proxy
In Java, a proxy class and a Invocationhandler interface are provided under the Java.lang.reflect package, and dynamic proxy objects can be generated by using this class and interface. The proxy provided by the JDK can only be proxied for the interface. We have more powerful proxies Cglib
A method in the proxy class creates a dynamic proxy class object
1, public static Object newproxyinstance (ClassLoader loader,class<?>[] Interfaces,invocationhandler h)
Returns a proxy class instance for the specified interface that can assign a method call to the specified invocation handler.
2. The method that will eventually call Invocationhandler
Invocationhandler
Object Invoke (Object Proxy,method method,object[] args): Processes the method call on the proxy instance and returns the result.
The three parameters of a method for creating a dynamic proxy object in the proxy class:
1. ClassLoader object:
Defines which ClassLoader object is to load the generated proxy object
2. An array of interface objects:
It means that I'm going to provide a set of interfaces to the object I need to proxy, and if I provide a set of interfaces to it, then the proxy object declares that it implements the interface (polymorphic) so that I can invoke the methods in this set of interfaces.
3. Invocationhandler object:
Indicates which Invocationhandler object the dynamic proxy object will be associated with when calling the method.
Note: Each dynamic proxy class must implement the Invocationhandler interface, and each instance of the proxy class is associated to a handler, and when we call a method through the proxy object, the method's
The call is forwarded to the Invoke method of this interface by Invocationhandler.
The three parameters of the Invoke method in the Invocationhandler interface:
- Proxy: Represents the Dynamic proxy object
- Method: Represents the methods being executed
- Args: Represents the argument passed in when the target method is called
Proxy.newproxyinstance
The proxy object created is an object that is dynamically generated when the JVM is run, and it is not our invocationhandler type.
Nor is it the type of interface that we define, but the one in which the run is dynamically generated, and the name is in this form,
Start with $, Proxy is medium, and the last number represents the label of the object.
System.out.println (U.getclass (). GetName ());
Overview and implementation of dynamic Proxy for Java 27-9 reflection