Reflection and Proxy Definition and Application

Table of contents

reflection

1. Why is there reflection

2. What is reflection

3. The way java creates objects: new objects, copying and deserialization of objects created by reflection

4. How to create objects and obtain class information through reflection

Step 1: Obtain the class object (the three methods correspond to the three stages respectively)

Step 2: Obtain class information (variables, methods, constructors, parent classes, interfaces, etc. are all class information)

 acting

1 proxy mode definition

2. Why there is a proxy mode/purpose of proxy

3. Three implementation methods: JDK static proxy, JDK dynamic proxy and CGLIB proxy

        ①, JDK static proxy

        ②, JDK dynamic agent

        ③, CGLIB agent


reflection

1. Why is there reflection

        To run a java program, the main method must be called, but there is no main method when learning to run a servlet

2. What is reflection

        Reflection is the ability to obtain class information

3. The way java creates objects: new object, copying and deserialization of objects created by reflection

Four ways to create objects in Java - qq_52240237's Blog - CSDN Blog

4. How to create objects and obtain class information through reflection

Step 1: Obtain the class object (the three methods correspond to the three stages respectively)

Step 2: Obtain class information (variables, methods, constructors, parent classes, interfaces, etc. are all class information)

        ①, get variables

getDeclaredFields( ): Get all types of variables, and the results are presented in an array

getFields( ): Get the public type, and the result is presented in an array

getDeclaredFiled( ): Get a single variable of all types, and the result is presented as a variable

getFiled(): Get a single public type, and the result is presented in a variable

        ②. Obtaining method

(Change the Filed in the variable to the method Method, the application method is the same as the variable)

(String.class uses reflection to refer to the class object)

        ③, Constructor

(Change the Filed in the variable to the constructor Constructor, the application method is the same as the variable)

The third step: operate on class information (variable assignment and value, method operation, object construction through constructor)

        ①, reflect the operation of the value

(For private data, it needs to be modified by violent reflection)

        ②, reflection on the operation of the method

        ③. The operation of anti-reflection pair constructor 

 5. The three stages that a java program goes through in a computer

(class class object, encapsulate data into an array)

(The class loader loads the .class file from disk into memory and encapsulates it with an array, and then loads it into the method area)

 acting

1 proxy mode definition

        Provide a proxy object to the target object and let the proxy object control the reference to the target object

2. Why there is a proxy mode/purpose of proxy

        ①. Enhanced function: Enhance the original business through agency business

        ②. Access control: Indirect access to target objects through proxy objects to prevent direct access to target objects from bringing unnecessary complexity to the system

3. Three implementation methods: JDK static proxy, JDK dynamic proxy and CGLIB proxy

        ①, JDK static proxy

                a. Realize proxy through inheritance

By inheriting the proxy object and rewriting the proxy method, it can be proxied.

Advantages : The proxied class does not need to implement the interface
Disadvantages : Only this class can be proxied. If you want to proxy other classes, you need to write new proxy methods if you want to proxy other classes.
Cglib dynamic proxy is to use this method to proxy classes. But classes are cglibdynamically generated in memory for us.

public class Tank{
    public void move() {
        System.out.println("Tank moving cla....");
    }

    public static void main(String[] args) {         new ProxyTank().move();     } } class ProxyTank extends Tank{     @Override     public void move() {         System.out.println("Before the method is executed...") ;         super.move();         System.out.println("After the method is executed...");     } }











 

                b. Realize agency through combination

        Defining an  Movable interface is required by both the proxy class and the proxy class to implement the interface. (The purpose of the interface here is to play a normative role to ensure that both the proxy class and the proxy class implement move()the method). The proxy class needs to use the interface as an attribute, and the object of the interface needs to be passed in when instantiating, so that the proxy class can realize the proxy of all implemented Movableclasses.

Advantages : It can proxy all classes that implement the interface.
Disadvantage : The proxied class must implement the interface.

JDK dynamic proxy is implemented in this way. The same proxy class is automatically generated in memory by JDK for us.

public class Tank implements Movable{
    @Override
    public void move() {
        System.out.println("Tank moving cla....");
    }

    public static void main(String[] args) {
        Tank tank = new Tank();
        new LogProxy(tank).move();
    }
}

class LogProxy implements Movable{
    private Movable movable;
    public LogProxy(Movable movable) {
        this.movable = movable;
    }
    @Override
    public void move() {
        System.out.println("方法执行前....");
        movable.move();
        System.out.println("方法执行后....");
    }
}
interface Movable {
    void move();
}
 

        ②, JDK dynamic agent

The classes provided by java Proxyhelp us create proxy objects.

Advantages : Proxy objects that implement all interfaces can be generated
Disadvantages : JDK reflection generation proxy must be interface-oriented, which is determined by the internal implementation of Proxy. In the method of generating the proxy, you must specify the interface of the implementation class, and it will implement the interface generated by the proxy class according to this interface.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * 使用jdk的动态代理
 */
public class Tank implements Movable{
    @Override
    public void move() {
        System.out.println("Tank moving cla....");
    }

    public static void main(String[] args) {         Tank tank = new Tank();         // reflection Reflection analyzes the properties and methods of the class through binary bytecode

        //newProxyInstance: Create a proxy object
        // Parameter 1: Proxied class object
        // Parameter 2: Interface class object The interface implemented by the proxy object
        // Parameter 3: Invoke the processor. How to deal with the method of the called object after being called
        Movable o = (Movable)Proxy.newProxyInstance(Tank.class.getClassLoader()
                ,new Class[]{Movable.class}
                ,new LogProxy(tank));
        o.move ();
    }
}

class LogProxy implements InvocationHandler {
    private Movable movable;

    public LogProxy(Movable movable) {
        this.movable = movable;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {         System.out.println("Method:"+method.getName()+"() before execution");         Object invoke = method. invoke(movable, args); // This is equivalent to movable.move()         System.out.println("Method:"+method.getName()+"() after execution");         return invoke;     } }





interface Movable {
    void move();
}
 

        ③, CGLIB agent

CGLib (Code Generate Library) is different from the JDK dynamic proxy in that the cglib generated proxy is a subclass of the proxied object. So it has inherited methods to implement static proxies

Advantages : There is no need for the proxy object to implement an interface.
Disadvantages : finalProxies cannot be generated for classes, because finalclasses cannot have subclasses.

<dependency>
     <groupId>cglib</groupId>
     <artifactId>cglib</artifactId>
     <version>3.2.12</version>
 </dependency>
 

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

public class Main {     public static void main(String[] args) {         Enhancer enhancer = new Enhancer(); // enhancer         enhancer.setSuperclass(Tank.class); // specify the parent class         enhancer.setCallback(new TimeMethodInterceptor()) ; // When called by the method of the proxy object, the object's intercept         Tank tank = (Tank)enhancer.create(); // Dynamic proxy generation         tank.move(); // Will be called after generation     } }







class TimeMethodInterceptor implements MethodInterceptor{     @Override     public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {         System.out.println("generated class name"+o.getClass().getName() );         System.out.println("The parent class of the generated class"+o.getClass().getSuperclass().getName());         System.out.println("The proxy method before the method is executed"+method .getName());         Object result = null;         result = methodProxy.invokeSuper(o, objects);         System.out.println("After the method is executed, the proxied method"+method.getName());         return result;     } } class Tank{     public void move(){













        System.out.println("Tank moving clacla....");
    }
}
 

Guess you like

Origin blog.csdn.net/qq_52240237/article/details/132181166