Reflection mechanism in Java

The reflection mechanism of Java is one of the characteristics of Java. The reflection mechanism is the basis of building framework technology. Java reflection mechanism refers to the function of dynamically obtaining information and dynamically calling object methods in the running state.

Java reflection has three dynamic properties: generating object instances at runtime, calling methods at runtime, and changing properties at runtime.

1, Common API s for Java reflection

Common classes using java reflection technology are as follows:

Class: the core class of reflection. All operations of reflection are generated around this class. Through the class, you can obtain the properties, methods and other content information of the class.

Field class: represents the property of the class. You can get and set the value of the property in the class.

Method class: represents the method of the class. It can obtain the information of the method in the class or execute the method.

Constructor class: represents the construction method of the class.

2, Application of reflection

1. Get class information

(1) There are three common methods to obtain Class objects

① Call the getClass() method of the object

Student s =new Student();//Student is a custom student type
Class c=s.getClass();

② Call the class attribute of the class

Class c=Student.class;//Student is a custom student type

③ Use the Class class's forName() static method. This method needs to pass in the string of the full name of a Class, that is, add the complete package name before the Class name

Class c=Class.forName("com.pb.jadv.Student");//correct

Class c=Class.forName(Student);//error

(2) Get information from Class object

 Class<Student> sc=Student.class;//Use type.class

① Access the constructor contained in the Class corresponding to the Class

Get construction method
//Get public constructor
 Constructor<Student> c = sc.getConstructor(int.class,double.class);
//Get all
 Constructor<Student> c = sc.getDeclaredConstructor(int.class,double.class,String.class);

② Access the methods contained in the Class corresponding to the Class

//Methods of accessing public
Method method = sc.getMethods(Method name, parameter type);
//Access all methods
Method method = sc.getDeclaredMethod(Method name, parameter type);

③ Access the properties contained in the Class corresponding to the Class

Field[] getFields(): returns the public attribute of the Class contained in this Class object

Field [] getdeclaraedfields(): returns all attributes of the Class contained in this Class object

2. Create object

There are two ways to create objects by reflection.

① Create an object using the newInstance() method of the Class object

The newInstance() method of the Class object is used to create an instance of the Class corresponding to the Class object. The corresponding Class of the Class object is required to have a default constructor. When the newInstance() method is executed, the default constructor is actually used to create an instance of the Class.

② Creating objects with a Constructor object

Specifying the construction method to create a Java object requires the following three steps:

Gets the Class object of the Class

Use the getConstructor() method of the Class object to obtain the specified constructor

Call Constructo's newInstance() to create an object

3. Access the properties of the class

//Use object to force property assignment
 Field stuNo = sc.getDeclaredField("stuNo");
 stuNo.setAccessible(true);//Get permission to value and assign private attributes
 stuNo.set(s,18);

4. Methods for accessing classes

//Calling methods using objects
    Method method = sc.getDeclaredMethod("getStuNo");//Get method by method name
    method.setAccessible(true);//Force access
    Object o = method.invoke(s);//Execute object method

5. Get parent class

Class<? super Student> suc = sc.getSuperclass();//Gets the Class object of the parent Class
Constructor<? super Student> cs = suc.getConstructor();//Gets the default constructor of the parent class
Object object = cs.newInstance();
System.out.println(object);

6. Get interface

Class<?>[] i = sc.getInterfaces();
Class<?> inter = i[0];//Get parent interface

public class Student extends Human implements Talkable{
    public int stuNo;
    private double score;
//    private Student() {
//    }

    public Student(int stuNo, double score) {
        this.stuNo = stuNo;
        this.score = score;
    }
    private Student(int stuNo, double score,String name) {
        this.stuNo = stuNo;
        this.score = score;
        setName(name);
    }

    private int getStuNo() {
        return stuNo;
    }

    private void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuNo=" + stuNo +
                ", score=" + score +
                '}'+getName();
    }
}
public class TestReflect<T> {
    public static void main(String[] args) throws Exception {
        //1. Get type Class
        Class<Student> sc=Student.class;//Use type.class
//        Student s=new Student();// Because the type of s cannot determine the specific object address (it may be a subclass type)
//        class<? extends Student>sc1=s.getClass();// Use object. class
//        Class<?>sc2=Class.forName("cn.kgc.Student");
        //2. Gets the construction method and creates the object
//        Constructor<Student> c = sc.getConstructor(int.class,double.class);// Get public constructor
        Constructor<Student> c = sc.getDeclaredConstructor(int.class,double.class,String.class);//Get all
        c.setAccessible(true);
        Student s=c.newInstance(3,88,"aa");//Creating objects by construction methods
        System.out.println(s);
//        System.out.println(s.getScore());
        System.out.println(s.getName());
        //3. Calling methods using objects
//        Method method = sc.getDeclaredMethod("getStuNo");// Get method by method name
        Method method = sc.getDeclaredMethod("setStuNo", int.class);
        method.setAccessible(true);//Force access
//        Object o = method.invoke(s);// Execute object method
        method.invoke(s,15);
//        System.out.println(o);
        System.out.println(s);
        //4. Use object to force property assignment
        Field stuNo = sc.getDeclaredField("stuNo");
        stuNo.setAccessible(true);
        stuNo.set(s,18);
        System.out.println(s);
        //5. Get parent class
        Class<? super Student> suc = sc.getSuperclass();//Gets the Class object of the parent Class
        Constructor<? super Student> cs = suc.getConstructor();//Gets the default constructor of the parent class
        Object object = cs.newInstance();
        System.out.println(object);
        Method think = suc.getMethod("think");
        think.invoke(object);
        //6. Get interface
        Class<?>[] i = sc.getInterfaces();
        Class<?> inter = i[0];//Get parent interface


    }
}

Tags: Java Back-end

Posted on Tue, 23 Nov 2021 12:10:17 -0500 by korngold