Moon geese fly high, all reflection knows——Analysis of java reflection mechanism

java reflection mechanism

Reflection mechanism concept

  • In the running state, for any class, all properties and methods of this class can be obtained, and for any object, any of its methods and properties (including private methods and properties) can be called. This dynamic acquisition The function of the information and the method of dynamically calling the object is called the reflection mechanism of the java language. Reflection is seen as the key to dynamic languages. Simply put, reflection is the mapping of various components of java into corresponding java classes.
  • In layman's terms, through reflection, this class is completely transparent to us, and we can get anything. Including construction methods, properties, methods.

Functions provided by java reflection

  • Judge the class to which any object belongs at runtime;
  • Construct an object of any class at runtime;
  • Judge the member variables and methods of any class at runtime;
  • Call any object method at runtime;
  • Generate dynamic proxy.

Java is not a dynamic language, but a dynamic mechanism is realized through reflection.

Basic use of reflection

The main components of java reflection

  • Class: Any class running in memory is an instance object of the Class class, and the memory of each Class class object contains all the original information. To do anything through reflection, you must first go to Class
    • Main information inside the class:
      • Field: all attributes
      • Constructor: all construction methods
      • Method: All methods
  • Field: describes the attributes of a class, and contains all the information of the attribute, such as data type, attribute name, access modifier
    • Main information inside the class
      • Annotation marked on the attribute
      • Attribute name
      • The data type of the attribute (boolean/double/int/String …)
      • Property access modifier (public/private/protected)
  • Constructor: describes the construction method of a class, which contains all the information of the construction method, such as parameter types, parameter names, and access modifiers
    • Main information inside the class
      • Access modifier for constructor
      • Parameters of the construction method
        • The data type of the parameter
        • The name of the parameter
        • Annotation marked on the parameter
  • Method: Describes all methods of a class (including abstract methods). It contains all the information of the method. It is similar to Constructor. The difference is that Method has return value type information because the constructor has no return value.
    • Main information inside the class
      • Main information inside the Constructor class
      • Method return value type (Int/double0

Steps to use reflection (obtain Class object, call object method)

  • Get the Class object of the class you want to operate, it is the core of reflection, through the Class object we can call the method of the class arbitrarily
  • Call the method in the Class class, which is the use stage of reflection
  • Use reflection API to manipulate this information

Reflective use

Example People

public class People {
    
    
    public String name;
    public int age;
    private double weight;
    
    public People(){
    
    }
    
    public People(String name,int age){
    
    
        this.name=name;
        this.age=age;
    }
    
    public void getInfo(){
    
    
        System.out.println(name+"的年龄是:"+age);
    }
}

Three methods of obtaining Class (obtaining the bytecode object of a class)

​ When compiled with javac, a .class file will be generated. When the bytecode file is loaded into the virtual machine for execution, a Class object will be generated in the memory, which contains all the information inside the class, during the program running stage This information can be obtained.

  • Use the object to obtain, use the object's getClass to obtain

    People people = new People();
    Class clazz=people.getClass();
    
  • Use static attribute class

    The Class object can only be obtained if the type of the class has been declared before compilation

    Class clazz =People.class;
    
  • Use the static method forName of the Class class ( get the Class object of the class by the fully qualified name of the class)

    • Full name of the class

      Class clazz = Class.forName("")
      

    When we get the class object, we can get class information, call its methods, and get its attributes.

Get all the information of a class

​ The Class object China contains all the information of the class. The information we can see during compilation is the variables, methods, and constructors of the class. The most commonly obtained information is also this information at runtime.

Each function is subdivided into two categories by Declared:

  • Declared modified method: you can get all the variables, methods and constructors contained in the class, but you cannot get the inherited information
  • Methods without Declared modification: You can get publicly modified variables, methods and constructors in this class, and get inherited information

If you want to get all the variables, methods and constructors in the class (including inheritance), you need to call them at the same time, and use the set collection to store the traversals they get, and one party gets the same things.

Get the variables in the class (Field)
  • Field[] getField(): Get all variables in the class that are modified by public
  • Field getField(String name): Get a variable in the class according to the variable name, and the change must be modified by public
  • Field[] getDeclaredFields): Get all the variables in the class, but cannot get the inherited variables
  • Field getDeclaredField(String name): Obtain the variables in the class according to the name, and cannot obtain the inherited variables
Get the method in the class (Method)
  • Method[] getMethods(): Get publicall methods that are modified in the class
  • Method getMethod(String name, Class…<?> paramTypes): Get the corresponding method according to the name and parameter type , the method must be publicmodified
  • Method[] getDeclaredMethods(): Get 所有methods, but cannot get inherited methods
  • Method getDeclaredMethod(String name, Class…<?> paramTypes): Obtain the corresponding method according to the name and parameter type , and cannot obtain the inherited method
Get the constructor of the class (Constructor)
  • Constuctor[] getConstructors(): Get all publicmodified constructors in the class
  • Constructor getConstructor(Class...<?> paramTypes): According to 参数类型obtain a constructor in the class, the constructor must be publicmodified
  • Constructor[] getDeclaredConstructors(): Get all constructors in the class
  • Constructor getDeclaredConstructor(class…<?> paramTypes): 参数类型Obtain the corresponding constructor according to

If the attribute of the parent class is modified with protected, it cannot be obtained by reflection

Get comments
  • Annotation[] getAnnotations(): Get all annotations on the object
  • Annotation getAnnotation(Class annotaionClass): Pass in 注解类型, get a specific annotation on the object
  • Annotation [] getDeclaredAnnotations (): Get all annotations explicitly marked on the object, can not get 继承down annotations
  • Annotation getDeclaredAnnotation (Class annotationClass): According to 注解类型acquire a specific comment on the object, can not get 继承down annotations

​ Only when the @Retension of the annotation is marked as RUNTIME, the annotation can be obtained through reflection

​ For details, please click: Annotation details

Invoke methods through reflection

​ After a Method class object is obtained through reflection, it can be executed by calling the invoke method

  • invoke(Oject obj, Object... args): Parameter ``1 指定调用该方法的**对象**,参数2` is the parameter list value of the method.
  • If the method called is a static method , parameter 1 only needs to be passed in null, because the static method is not related to a certain object, only a certain class.

Application scenarios of reflection

There are three common scenarios:

  • Spring instantiated objects: When the program starts, Spring will read the configuration file applicationContext.xml and parse out all the tags inside and instantiate them into the IOC container
  • Reflection + Engineering Mode: Eliminate multiple branches in the factory through reflection. If you need to produce new classes, focus on the factory classes disorderly. The factory classes can deal with various new classes. Reflection can make the program more robust.
  • JDBC connect to the database: when using JDBC to connect to the database, the reflective loading startup class is used when specifying the driver class to connect to the database

Spring's IOC container

​ In Spring, a context configuration file applicationContext.xml is often used for bean configuration. When the query starts, the xml file is read, all the tags are parsed, and the object is instantiated and placed in the IOC container, IOC The container is essentially a factory, and the corresponding instance is obtained by passing in the id attribute of the label through the factory.

​ After the process of instantiating an object in Spring is simplified, it can be understood as the step of reflecting the instantiating object

  • Get the constructor of the Class object
  • Instantiate the object by calling newInstance() through the constructor

Of course, Spring does a lot of extra operations when instantiating objects to make current development convenient and stable

Reflection + abstract engineering mode

​ In the traditional engineering mode, if you need to produce new sub-categories, you need to modify the factory category and add new branches to the factory category.

​ Using the combination of reflection and factory mode, when producing new subclasses, the factory class does not need to modify anything, and can focus on the implementation of the subclass. When the subclass is determined, the factory can also generate the subclass.

The core idea of ​​reflection + abstract factory is:

  • At runtime, pass in the fully qualified names of different subclasses through parameters to obtain different Class objects, and call the newInstance() method to return different subclasses.

JDBC load database driver class

​ When importing third-party libraries, the JVM will not take the initiative to load the externally imported classes, but will only load the required classes when they are actually used. Because of this, we can pass in the driver class when getting the database connection Fully qualified name, hand over to JVM to load the class

Pros and cons of reflection

Advantages of reflection:

  • Increase program flexibility: In the face of changes in requirements, different objects can be instantiated flexibly

Disadvantages of reflection:

  • Destroy the encapsulation of the class: you can force access to privately modified information
  • Performance loss: Compared with directly instantiating objects, calling methods, accessing variables, reflection requires a lot of inspection steps and parsing steps, and JVM cannot optimize it

Reflection summary

  • The idea of ​​reflection: reflection is like a mirror, only at runtime can you see who you are, get your own information, and even instantiate objects
  • The role of reflection: the instantiated object is determined at runtime, which makes the program more robust. In the face of changes in requirements, it can respond to different scenarios and instantiate different types of objects to the greatest extent without modifying the program source code. .
  • Application scenarios of reflection: Spring's IOC container; reflection + factory mode, making the factory class more stable; loading the driver class when JDBC connects to the database
  • Three characteristics of reflection: increase the flexibility of the program, destroy the encapsulation of the class and performance loss

At last

  • If you feel that you are rewarded after reading, I hope to give me a thumbs up. This will be my biggest motivation for updating. Thank you for your support.
  • Welcome everyone to pay attention to my official account [java Toka Fox], focus on the basic knowledge of java and computer, and ensure that you will get something after reading it. If you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, welcome to comment and share. Thank you for your support and love.

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/108342487