Detailed explanation of Java dynamic proxy mechanism (JDK and CGLIB, Javassist, ASM)

The principle of dynamic proxy

javasist --> way 

    1. Get a list of all interfaces on RealSubject;
    2. Determine the class name of the proxy class to be generated, the default is: com.sun.proxy.$ProxyXXXX;

    3. According to the interface information to be implemented, dynamically create the bytecode of the Proxy class in the code;

    4. Convert the corresponding bytecode to the corresponding class object;

    5. Create an instance handler of InvocationHandler to handle all method calls of Proxy;

    6. The class object of Proxy takes the created handler object as a parameter and instantiates a proxy object

The pattern for cglib to create a dynamic proxy class for a class A is:

1. Find method definitions of all non-final public types on A;

2. Convert the definitions of these methods into bytecode;

3. Convert the composed bytecode into the corresponding proxy class object;

4. Implement the MethodInterceptor interface to process requests for all methods on the proxy class (this interface has the same function and role as the JDK dynamic proxy InvocationHandler)

Introduction to Java bytecode generation open source framework --ASM :

ASM is a Java bytecode manipulation framework. It can modify existing classes in binary form or dynamically generate classes. ASM can generate binary class files directly, or dynamically change class behavior before classes are loaded into the Java virtual machine. After ASM reads information from class files, it can change class behavior, analyze class information, and even generate new classes according to user requirements.

However , in the process of creating class bytecode, ASM operates at the assembly instruction level of the underlying JVM , which requires ASM users to have a certain understanding of the class organization structure and JVM assembly instructions.

 

Reference documentation 

https://blog.csdn.net/luanlouis/article/details/24589193

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325161679&siteId=291194637