Java reflection mechanism

Posted by daleks on Fri, 14 Jan 2022 04:07:09 +0100

1, What is reflection?

Reflection: the ability of a program to access, detect, and modify its own state or behavior.

The core of Java reflection mechanism is to dynamically load classes or obtain class information in class objects when programs run, so as to operate the properties and methods of classes or objects.

2, Advantages and disadvantages of reflection

  • advantage

    1. Dynamically load additional resources during operation;

    2. Dynamically access and modify class information and related class behaviors during operation;

    3. Dynamically create instance objects, decouple them from the explicit creation of the program, and improve the scalability of the program;

  • shortcoming

1. Reflection will consume certain system resources due to the dynamic loading of class information by the JVM;

2. When reflection changes class behavior, permission check can be ignored, which may destroy encapsulation and lead to security problems;

3, Three stages of Java program execution

  • Source source phase: * java is compiled into * class bytecode file;

  • Class object stage: * The class bytecode file is loaded into the memory by the class loader (preparation - > verification - > parsing);

  • Runtime runtime phase: create instance objects according to class definition information;

4, How to get a Class object

  • Source source code stage: class Forname ("full class name"), the return value is the class object;

  • Class object stage: class name Class, obtained through the attribute class of the class name;

  • Runtime runtime phase: Object getClass(), the getClass() method is defined in the Object class;

Additional extension: method setAccessible(true); // Violent reflex

@Test
public void reflect1() throws ClassNotFoundException {
    //Method 1: class Forname ("full class name");
    Class cls1 = Class.forName("com.test.domain.Person");   //Person custom entity class
    System.out.println("cls1 = " + cls1);


    //Method 2: class name class
    Class cls2 = Person.class;
    System.out.println("cls2 = " + cls2);


    //Method 3: object getClass();
    Person person = new Person();        
    Class cls3 = person.getClass();
    System.out.println("cls3 = " + cls3);


    // ==Compare three objects
    System.out.println("cls1 == cls2 : " + (cls1 == cls2));    //true
    System.out.println("cls1 == cls3 : " + (cls1 == cls3));    //true
    //Conclusion: the same bytecode file (*. class) will only be loaded once during a program run, and the class object obtained by either method is the same.
}

The execution results are as follows:

5, Common classes of reflection mechanism

  • Java.lang.Class;

  • Java.lang.reflect.Constructor;

  • Java.lang.reflect.Field;

  • Java.lang.reflect.Method;

  • Java.lang.reflect.Modifier;

6, How to manipulate Class objects

1) get member variables

Field[] getFields();//Gets the member variables of all public modifiers
Field getField(String name); //Gets the member variable of the public modifier with the specified name
Field[] getDeclaredFields(); //Gets all member variables, regardless of modifiers
Field getDeclaredField(String name);

2) obtain the construction method

Constructor<?>[] getConstructors();  
Constructor<T> getConstructor(class<?>... parameterTypes);  
Constructor<?>[] getDeclaredConstructors();
Constructor<T> getDeclaredConstructor(class<?>... parameterTypes); 

3) Get member methods

Method[] getMethods();
Method getMethod(String name, class<?>... parameterTypes); 
Method[] getDeclaredMethods();
Method getDeclaredMethod(String name, class<?>... parameterTypes);

4) get the full class name

String getName();

7, Case

(1) Person class

package com.test.domain;

public class Person {
    //Nonparametric method
    public void eat(){
        System.out.println("eat...");
    }
}

(2) Write configuration file (pro.properties)

className = com.test.domain.Person
methodName = eat

(3) Writing test methods

package com.test.junit;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

public class ReflectTest {

    public static void main(String[] args) throws Exception {
        /**
         * Premise: you cannot change any code of this class. You can create objects of any class and execute any method
         * That is, hard coding is rejected
         */
        //1. Load configuration file
        //1.1 create Properties object
        Properties pro = new Properties();
        //1.2 load the configuration file and convert it into a collection
        //1.2.1 get the configuration file under the class directory and use the class loader
        ClassLoader classLoader = ReflectTest.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("pro.properties");
        pro.load(is);

        //2. Obtain the data defined in the configuration file
        String className = pro.getProperty("className");
        String methodName = pro.getProperty("methodName");

        //3. Load this class into memory
        Class cls = Class.forName(className);
        //4. Create object
        Object obj = cls.newInstance();
        //5. Get method object
        Method method = cls.getMethod(methodName);
        //6. Implementation method
        method.invoke(obj);
    }
}

(4) operation results

 

Topics: Java