Reflection of java Foundation

Posted by justinchrono on Mon, 03 Jan 2022 04:53:53 +0100

definition

The reflection system of java is that during the running process, we can know all its properties and methods for any class, and we can call all its properties and methods for any object. Such a dynamic operation of modifying and calling information is called reflection.

Why use reflection

Let's answer this question through some words in the official Oracle documents:

  • Reflection allows developers to create objects through the full pathname of external classes and use these classes to achieve some extended functions
  • Reflection allows developers to list all members of a class, including constructors, properties, and methods. To help developers write the right code
  • When testing, you can use the reflection API to access the private members of the class to ensure the coverage of the test code

Use of reflection

Overview map

This is the Person class we want to use

public class Person {
    public String name;
    public int age;
    private int money;

    public Person(String name, int age, int money) {
        this.name = name;
        this.age = age;
        this.money = money;
    }

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", money=" + money +
                '}';
    }
}

Class class

What is a Class
  • After the java file is compiled, it will be generated Class bytecode file, and the bytecode file will be loaded into the JVM. Then the JVM will parse the class to be used into an object, which is the object of class class, which is stored in the JVM heap. In the reflection mechanism, we can create class instances through this class object, obtain class properties, modify class properties, call class methods, and so on.

  • For each class, the JVM will create an instance of class. Whenever we write and create a new class, a class object will be created, and the class object will be saved in Class file

  • No matter how many instances of a Class are created (such as the Person Class below), there is only one Class object in the JVM

  • Class is the basis of reflection. If you want to obtain an instance of a class (such as the Person class below), you must create a class object to obtain it

Class related methods
methodexplain
forName(String className)Returns the object of the class according to the class name
newInstance()Create an instance of a class
getName()Get the full path name of the class

Three ways to get objects of Class

  1. Use by calling Class's static method forName("full pathname") (this method needs to throw an exception because the pathname may be written incorrectly)

    You only need to know the full pathname. This method will load if the Class has not been loaded, and return the Class object if the Class has been loaded

    Class cls1 = Class.forName("Java Advanced features.reflex.Person");
    
  2. Create a class object by calling the class attribute of the Person class

    This method is more suitable for such known situations

    Class cls2 = Person.class;
    
  3. Created by calling the getClass() method of the Person class object

    You need to create a Person class object to use it

    Person person = new Person("1", 1, 1);
    Class cls3 = person.getClass();
    
public static void main(String[] args) throws Exception {
    //1. Call the forName("full pathname") method of Class class to create
    Class cls1 = Class.forName("Java Advanced features.reflex.Person");
    //2. Call the class attribute of the Person class to create a class object
    Class cls2 = Person.class;
    //3. Call the getClass() method of the object of the Person class to create it (this method requires an object of the Person class)
    Person person = new Person("1", 1, 1);
    Class cls3 = person.getClass();

    //Compare whether the three creation methods are equal
    System.out.println(cls1 == cls2);		//true
    System.out.println(cls1 == cls3);		//true

    /*
    From the above, we can see that the three creation methods are equivalent. The Person class will only be loaded once in the JVM
     */
}

Field class

Operate on member variables

Field class related methods
methodexplain
Field getFiled(String name)Get a public property object
Field[] getFileds()Get all public property objects
Field getDeclaredFiled(String name)Get a property object
Field[] getDeclaredFileds()Get all attribute objects
void set(Object obj, Object value)Sets the value of the corresponding member variable of the object
Object get(Object obj)Gets the value of the corresponding member variable of the object
void setAccessible(boolean flag)When accessing the private member variable, it needs to be set to true, and brute force access (the method needs to throw an exception)
package Java Advanced features.reflex;

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws Exception {
        Class cls = Person.class;
        //Access member variables
        /*
            Class Class object getFields(): get the member variable decorated with public
            Class Class object Getdeclaraedfields(): get all member variables
         */
        Field[] fields = cls.getFields();
        System.out.println("Public member variable:");
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("All member variables:");
        fields = cls.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        Person person = new Person("Zhang San", 18, 100);
        //Gets a specific member variable
        Field field = cls.getField("name");
        System.out.println(field);
        System.out.println(field.getName());
        System.out.println(field.get(person));
        //Modify specific member variables
        field.set(person, "Li Si");
        System.out.println(field.get(person));
        //Access private decorated member variables
        field = cls.getDeclaredField("money");
        field.setAccessible(true);
        System.out.println(field.get(person));
        field.set(person, 200);
        System.out.println(field.get(person));

    }
}

Constructor class

Operate on the construction method

Constructor class related methods
methodexplain
getConstructor(Class...<?> parameterTypes)Get the public constructor in the class that matches the parameter type
getConstructors()Get all public constructors of the class
getDeclaredConstructor(Class...<?> parameterTypes)Get the constructor matching the parameter type in the class
getDeclaredConstructor()Get all constructors of this type
T newInstance(Object ... initargs)To create a Person object through the Constructor object, you need to pass the parameters of the Person object and method
package Java Advanced features.reflex;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws Exception {
        Class cls = Person.class;
        //Gets the constructor decorated with public
        Constructor[] constructors = cls.getConstructors();
        System.out.println("with public Construction method of modification:");
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("with private Construction method of modification:");
        constructors = cls.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        Constructor constructor = cls.getConstructor(String.class, int.class, int.class);
        //Use constructors to create objects (all constructors can be used)
        Person person = (Person)constructor.newInstance("Zhang San", 18, 100);
        System.out.println(person.getName());
        //Create objects using Class objects (only parameterless constructors can be used)
        person = (Person)cls.newInstance();
        System.out.println(person.getName());

    }
}

Method class

Operate on member methods

Method class related methods
methodexplain
getMethod(Class...<?> parameterTypes)Gets the public method in the class that matches the parameter type
getMethods()Get all public methods of the class
getDeclaredMethod(Class...<?> parameterTypes)Gets the method in the class that matches the parameter type
getDeclaredMethods()Get all methods of this type
Object invoke(Object obj, Object... args)To call the method of the Person object, you need to pass the parameters of the Person object and method
package Java Advanced features.reflex;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws Exception {
        Class cls = Person.class;
        //Gets the member method decorated with public (containing the parent class)
        System.out.println("with public Decorated member method:");
        Method[] methods = cls.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        //Get all member methods (excluding those of the parent class)
        methods = cls.getDeclaredMethods();
        System.out.println("All member methods:");
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("Call method:");
        Person person = new Person("Zhang San", 18, 100);
        Method method = cls.getMethod("getName");
        System.out.println(method);
        System.out.println(method.invoke(person));

    }
}

Create an object of the Person class

Created by Class object
Class cls = Class.forName("Java Advanced features.reflex.Person");
Person person = (Person) cls.newInstance();	//Forced rotation is required because Class The type returned by the newInstance() method is Object type
Created from a Constructor object
Constructor constructor = cls.getConstructor(String.class, int.class, int.class);
person = (Person) constructor.newInstance("1", 1, 1);//Strong rotation, because the Constructor class The type returned by the newInstance() method is Object type

Advantages and disadvantages of reflection

advantage:

  • For any class, you can know all the properties and methods of the class; For any object, you can modify all properties of the object and call all methods and properties of the object
  • You can manipulate these objects while the program is running.
  • It can decouple and improve the scalability of the program.

Disadvantages:

  • Reflection technology bypasses the source code, which will bring maintenance problems
  • Reflective code is more complex than direct code

Topics: Java Back-end