Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does Java dynamic proxy mean?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what does Java dynamic agent refer to". In daily operation, I believe that many people have doubts about what Java dynamic agent refers to. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what does Java dynamic agent refer to?" Next, please follow the editor to study!

I. static agent

Before describing a dynamic proxy, take a look at the static proxy.

Define a programmer's interface and do only two things (programmers are too busy to do anything else)

The Java programmer looks like this. He can develop Java code and debug Java code.

There is a tough programmer named Farmerbrag who prays before developing so that the code he develops will not have bug.

Let's describe Farmerbrag (proxy class) this way.

If Farmerbrag is just an ordinary Java programmer, then his development result is

Farmerbrag is coding java.

Farmerbrag is debugging java.

The real Farmerbrag (Farmerbrag proxy class) looks like this

Farmerbrag is praying for the code!

Farmerbrag is coding java.

Farmerbrag's code is bug-free and does not require debugging

Forget the advantages of static agency and talk about the disadvantages.

1. Increase the complexity of code maintenance. The proxy class and the implementation class have the same interface, and the proxy class executes specific methods through the implementation class. This leads to a lot of code duplication. If a method is added to the interface, all proxy classes also need to implement this method, in addition to all implementation classes.

2. Proxy objects serve only one type of object. If you want to serve multiple types of objects and proxy for each type of object, static proxies are not competent when the program is a little larger.

2. Examples of dynamic agents

Following the example of static proxies, Farmerbrag will pray that this feature is unique to him and that other programmers will not. (do you feel that some business needs want this scenario very much)

In fact, we do not need to define him, this skill can be acquired. See how to do it?

The programmer of this dynamic agent executes as follows

Farmerbrag is praying for the code!

Farmerbrag is coding java.

Farmerbrag's code is bug-free and does not require debugging

The type of farmerbragProxy is the Developer interface, not an implementation class. The objects generated by farmerbrag after being proxied do not belong to any of the implementation classes of the Developer interface, but are loaded with proxies based on the Developer interface and farmerbrag classes. (how can the mapper interface defined by mybatis be called and executed)

Look at the definition of the newProxyInstance () interface

Including three parameters

Loader and interfaces decide what kind of class this class is. And h is InvocationHandler, which determines what function is added to this proxy class. So the content of the dynamic agent focuses on this InvocationHandler.

The example of a dynamic proxy uses lambda expressions, and the main code is the implementation of InvocationHandler.

III. Code analysis

From the point of view of writing code, the first two sections are enough, and the principle is analyzed below.

Look at the key parts of the source code. There are several paragraphs in the newProxyInstance () method

1. Clone API

2. Find or generate the specified proxy class

3. Get the constructor of the proxy class through reflection

4. Use the constructor to new an object and associate with InvocationHandler

It may be more confusing to see some people here. What on earth does InvocationHandler do? What about reflect? How on earth has the code been changed?

Fourth, principle analysis

1. Class file and its loading (reflection)

The compiler compiles the Java file and produces a .class file to be stored on disk. The content of the file is machine code that only the JVM virtual machine can recognize. The JVM virtual machine reads the bytecode file, takes out the binary data, loads it into memory, parses the information in the .class file, and generates the corresponding Class object

Demonstrate the process of manually loading class file bytecodes into the system, converting them into class objects, and then instantiating them through a piece of code.

We reuse the previous JavaDeveloper.class for the loaded class

Customize a class loader

Execute the code to get the following result

Net.fengyu.proxy.JavaDeveloper

Farmerbrag is coding java.

The above code demonstrates the process of loading into a class object through bytecode

2. Binary bytecode is generated at run time

JVM loads the class through the bytecode binary information. If we follow the format and structure of the .class file organized by the Java compilation system in the runtime system, generate the corresponding binary data, and then load the binary data into the corresponding class, thus completing the ability to dynamically create a class in the code. The second section of the dynamic proxy example is clearly a subset of this capability.

There are some open source frameworks that support run-time bytecode generation, such as ASM,Javassist

ASM is a Java bytecode manipulation framework. You can modify existing classes or dynamically generate classes in binary form. ASM can generate binary class files directly, or it can dynamically change the class behavior before it is loaded into the Java virtual machine. The CGLIB used by Spring also uses the ASM framework as its bytecode manipulation tool.

The following code generates a class ASMDeveloper that is almost the same as the previous JavaDeveloper, which runs with the same output using the LoadClass class in the previous section

This example shows that it is possible to create an instance by generating bytecode in the code and dynamically loading it into a class object. It is certainly possible to modify a class dynamically (that's what dynamic proxies do).

At this point, the principle level has been basically made clear.

3. Why InvocationHandler

We already have the ability to dynamically modify the code of a class, and even if we use ASM to generate a very simple class, the amount of code is numerous and complex. Think carefully about the agent Proxy role in the agent mode. When Proxy roles perform proxy business, they simply do some "extra" business before or after invoking the real business.

The logic of the proxy class is simple, doing some extra business before and after calling a method. Another way of thinking is to do some extra business before or after the method of invoke the real character. In order to construct a generic and simple proxy class, all the actions that trigger the real character can be handed over to a trigger manager. This kind of manager is InvocationHandler.

In this pattern, the proxy Proxy and RealSubject need to implement the same function (functional method).

In object-oriented programming, there are two ways to agree that Proxy and RealSubject implement the same function (functional method).

Define a functional interface that both Proxy and RealSubject implement.

B. Through inheritance, Proxy inherits from RealSubject, so Proxy has the function of RealSubject

The mechanism for creating dynamic agents provided in JDK uses an idea, while cglib uses b idea (spring uses both).

At this point, the study of "what does Java dynamic agent refer to" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report