Welcome to “Algorithms and the Beauty of Programming” ↑ pay attention to us!
This article was first published on the wechat official account “Beauty of Algorithms and Programming”. Please follow us and learn more about this series of articles in time.
Why dynamic proxy
Last time we analyzed the principle of static proxy pattern in detail, and implemented a simple static proxy case with code. But we will find that in the static agent in the proxy class and proxy class needs to implement the same interface, this means that one of our static proxy class agent only one class, and will know in advance, we are going to the agent which class to write a proxy class, if we have other classes would also like to use a proxy that must be to write a proxy class. However, in real development we may have a large number of classes that need to be proxied, and we may not know in advance which class we want to proxiate. So continuing to use static proxies would add a lot of work, be inefficient, and have poor code reuse. The JDK provides us with the concept of dynamic proxy, where a single proxy class implements all propped operations. Let’s take a closer look at how dynamic proxies work.
2 Dynamic Proxy
2.1 What is dynamic proxy
We learned earlier that static proxies mean that the proxy class exists before the program runs. On the contrary, the proxy class of dynamic proxy does not exist before the program runs, that is, the proxy mode created by the proxy class when the program runs becomes dynamic proxy. In this case, the proxy classes are not defined in Java code, but are dynamically generated at runtime based on our “instructions” in Java code. Let’s take a look at an example of how dynamic proxy works.
2.2. Dynamic proxy simple implementation
Again, in our previous example, students in a class submit their homework to the teacher, but the teacher does not accept everyone’s homework directly, but gives it to the study committee, who then passes it on to the teacher. We’re going to implement it today with dynamic proxies. We continue to use the Person interface and Student class written before. Please refer to the previous blog “Java Proxy Mode Implementation and Detailed Explanation (I)” for specific code implementation.
Let’s start by writing a proxy class, MyProxy, that implements dynamic proxies. The code is as follows:
As you can see, this class implements an interface called InvocationHandler, introduces generics, and overrides the invoke() method, where we print a sentence to record which method our agent executes. So why do it? We’ll talk about it in detail below.
The proxy class is already written, so let’s see how to implement dynamic proxy. Write a Test class, test.java, to Test our dynamic proxy.
Running results:
As we can see from the code, we first create an object to be proxied, then create an InvocationHandler object handler and bind the object to be proxied to it. Then we created a proxy object, stuProxy, and passed handler as a parameter. Finally, the submitHomework method was executed through stuProxy to complete the proxy.
In the proxy class we do not declare which class we want to proxy but in our test class, that is, we create the proxy object we want to proxy, pass it into the proxy class, and finally complete the proxy, this is the dynamic proxy mode.
In the Proxy class we implement an InvocationHandler interface, and in the test class we invoke a Proxy class, which completes the dynamic Proxy function, so why do we do this? What do they stand for? Let’s analyze the principle in detail.
3 Dynamic proxy principle analysis
3.1. InvocationHandler interface
If you want to implement the dynamic proxy pattern, you must first observe an interface:
java.lang.reflect.InvocationHandler; Let’s look at the source code of this interface:
Inside this interface we can see that it has only one invoke() method. So what does the invoke() method do? There are three parameters in this method. What do these three parameters represent? Let’s look at the comments inside:
This interface explains the functions of the three parameters in detail. Let’s summarize:
Object Proxy: indicates the Object of the proxy class.
Method Method: indicates the Method being invoked.
Object[] args: Indicates the parameters received in the interface method, or null if the interface method does not use parameters.
Let’s see what the return type is:
We know from the comments given that the value returned by this method must be an instance of the corresponding base wrapper object class. That is, to return our proxy object, so this method is an action method in the proxy class that calls the real subject class, the proxied class. However, we can find that there is no corresponding proxy object in this method, so we set the real operation object when creating this class object. So how do we set that up? In fact, we have already demonstrated this in the above case. To find the Proxy object, we create it dynamically using the java.lang.Reflect. Proxy class. How is this class created? We analyze it in detail according to its source code.
3.2. Java. Lang. Reflect. The Proxy class
In this class we focus on one method:
public static Object newProxyInstance(ClassLoader loader,Class<? >[] interfaces,InvocationHandler h)throws IllegalArgumentException ; Returns an instance of a proxy class that assigns a method call to the specified invocation handler. It is this approach that implements our dynamic proxy functionality. Let’s first look at the parameters in this method:
ClassLoader: refers to the loader that obtains objects.
Class
[] interfaces: The core of the proxy design pattern is around interfaces, and we must extract all interfaces. So this parameter refers to the list of interfaces that the proxy class will implement.
InvocationHandler h: the implementation class of the proxy that assigns the InvocationHandler to the method invocation.
Let’s look at the implementation code for this method:
NullPointerException = NullPointerException = NullPointerException = NullPointerException = NullPointerException = NullPointerException = NullPointerException Let’s move on to the code:
This code is the core method to implement dynamic proxy. The idea of dynamic proxy is actually to generate a new class.
Let’s move on:
Again, let’s start with a code comment that says: call its constructor with the specified call handler, that is, an instance of a proxy class with the specified interface. Now we can see why we use this method to set the actual action object we mentioned above. Let’s go back to the example code we wrote earlier:
It is through the proxy.newProxyInstance method we mentioned above that we set up the real action object to accomplish dynamic Proxy. The first argument to the method we pass through the classloader to get the object that we want to delegate, the second argument we get the list of interfaces that the proxy class is going to implement in the Person class, and finally the third argument we pass in the implementation object of the proxy class. With this method we get a proxy object for Person. The proxy operation is finally done through the proxy object.
4 summarizes
This article has done the detailed analysis to Java dynamic Proxy, and has realized a simple dynamic Proxy case, the realization dynamic Proxy is a key interface InvocationHandler and a class Proxy. The dynamic proxy example above is a simple implementation of AOP. Proxy and InvocationHandler are also used in Spring’s AOP implementation. However, we can find from the Proxy class that the Java dynamic Proxy we analyze in this article can only implement the Proxy for the interface, not the dynamic Proxy for the class. Does that mean we can’t use dynamic proxy without an interface? Is there a proxy that doesn’t rely on interfaces?
\
More interesting articles:
Where2go team
Wechat: The beauty of algorithms and programming
Long press to identify the QR code to follow us!
Tips: Click on the lower right corner of the page “Write a message” to comment, looking forward to your participation! Looking forward to your forwarding!