Java improves Part 8 dynamic agent technology

For dynamic agents, those who have learned AOP should not be unfamiliar, because agents are the core and key technology to realize AOP functions. So today we'll start learning about dynamic agents:

1、 Export dynamic proxy

Agents should be very common in life. For example, you can buy computers through agents or directly find manufacturers to buy computers. Finally, you buy computers. There are also agents in the program. For example, to add some system functions to the existing methods of multiple target classes with the same interface, such as exception handling, logging, time-consuming calculation methods, etc., what will we do?

1. I will write a proxy class with the same interface as the target class. Each method of the proxy class calls the same method of the target class, and then add the code required by the system function before and after calling the method.

2. If the factory mode or configuration file is used for management, there is no need to modify the client program. Configure whether to use the target class or proxy class in the configuration file, so that it is easy to switch in the future.

Examples are as follows:

Now I want to add a time before the method and a time after the method to calculate the total execution time of the method If I don't get the sayhello source code, what should I do? Write a proxy:

Note: the above is pseudo code.

Just put the start time and end time before and after this method Usually we let two methods implement the same interface Then, if the client wants to use x, it can also use xproxy The specific schematic diagram is shown in the figure below:

2、 Create a dynamic proxy class

Now imagine that the above only represents a target class. If there are multiple target classes, do you want to create N multiple proxy classes? It's not that the code is too inflexible and cumbersome. Of course not.

Java virtual machine can dynamically generate classes during operation, which are generated in the form of bytecode. Such dynamically generated classes are often proxy classes. Dynamic proxy class.

The dynamic proxy class generated by the JVM must meet certain conditions, that is, it must implement one or more interfaces. Therefore, the dynamic proxy generated by the JVM can only be used as the proxy of the target class with the same interface. (the dynamically generated class is not a proxy. We just use this class as a proxy.)

API of proxy dynamic proxy:

Two parameters should be easy to understand:

The first parameter: we know that any bytecode needs to be loaded through the classloader, so the dynamically generated bytecode is no exception. We need to give it a classloader.

The second parameter is a condition that must be met for dynamic proxy class generation. One or more interfaces need to be implemented. Otherwise, there will be no method in the generated class bytecode, and its functional significance will be lost if there is no method.

Let's create a dynamic proxy class. The general idea is as follows:

1. Create a dynamic class that implements the collection interface, view its name, and analyze the proxy Parameters of getproxyclass method

2. Code lists all construction methods and parameter signatures in the dynamic class

3. Code lists all method and parameter signatures in the dynamic class

4. Create an instance object of a dynamic class: 1) use reflection to obtain the construction method; 2) write the simplest invocationhandle class; 3) call the construction method to create an instance object of a dynamic class and pass the instance object of the invocationhandle class into it; 4) print the unreturned methods and getClass methods of the created and called objects, The demo reported an exception when calling other methods with return values.

5) The proxy that creates the instance object of the dynamic class is written as an anonymous inner class to simplify the code.

The example is implemented step by step as follows:

(1) First, let's complete the previous 3 steps:

The output results are as follows:

$Proxy0 ----------begin constructors list---------- $Proxy0(java.lang.reflect.InvocationHandler) ----------begin methods list---------- add(java.lang.Object) hashCode() clear() equals(java.lang.Object) toString() contains(java.lang.Object) isEmpty() addAll(java.util.Collection) iterator() size() toArray([Ljava.lang.Object;) toArray() remove(java.lang.Object) containsAll(java.util.Collection) removeAll(java.util.Collection) retainAll(java.util.Collection) isProxyClass(java.lang.Class) getProxyClass(java.lang.ClassLoader,[Ljava.lang.Class;) getInvocationHandler(java.lang.Object) newProxyInstance(java.lang.ClassLoader,[Ljava.lang.Class;,java.lang.reflect.InvocationHandler) wait() wait(long,int) wait(long) getClass() notify() notifyAll()

You can see that all the methods are from the collection and the methods in the parent class object, which is in line with our expected results. Next, we move to the implementation of step 4 and step 5:

First, let's create an instance of this dynamic proxy class. Then directly clazzproxy1 newInstance(); Can I? Obviously not We just said that the dynamically generated proxy class has only one constructor. Is there a parameterless constructor? Not at all. So, create a parameter constructor The parameter type is Java lang.reflect. InvocationHandler。

Let's implement it below:

1. Define an instance of the above interface:

2. Call the implementation to create an instance dynamic class:

3. We use anonymous inner classes to optimize:

4. Continue to optimize: think about it. If we want to create a dynamic proxy class in the above way every time, it is a little repetitive. This is a simple method provided in the proxy class of JDK to directly create a dynamic proxy class. The method is as follows:

3、 Simple analysis of the principle of dynamic agent

Above, we created a dynamic proxy class. Below, we analyze the principle of proxy:

Here's a question:

Working principle of dynamic agent:

For the graph above, we can simply say: the client dynamically generates the proxy class, then calls the proxy class method, and the proxy class calls handler. internally. Invoke () method. In invoke, we point to the target class This implements the proxy When I call any method of the proxy from the client, invoke only the same method of the target class Before and after specifying the target class method, we can also do other operations, such as logging The part circled in the figure is the function implemented by the proxy class itself This is the principle of proxy classes

Let's take the last step to write a general method for generating agents and inserting announcements by using the dynamically generated agent class above:

Test code:

4、 Implement spring like configurable AOP framework

First, we need to complete the following requirements:

Let's simulate spring's factory pattern and read the classes passed from the configuration file. If this class is a normal class, it returns directly. If it is a proxy class, create a proxy object and return the proxy class.

See the picture above for specific theoretical knowledge

First create a beanfactory Java class. This is a bean factory for reading classes in the configuration file

If the class contains a proxyfactorybean, the getproxy method in the proxyfactorybean is called. Dynamically generate proxy classes. Proxyfactorybean. java

Next, create a config Properties file config. Properties

xxx=java. util. ArrayList #xxx=study. javaenhance. aopframework. Proxyfactorybean xxx. advice=study. javaenhance. MyAdvice xxx. target=java. util. ArrayList

Finally, establish the test class:

Test OK

Summary: the whole Java enhanced video learning is completed. I don't know how much I remember But I know a lot of internal knowledge. If I have time, or say for a period of time, I can ask and provide my own skills.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>