Reflection mechanism of Java

Posted by scristaldi on Thu, 18 Nov 2021 01:54:56 +0100

preface

A program that can analyze class capabilities is called reflection. The reflection mechanism in Java is very powerful. The reflection mechanism can be used to:
• the ability to analyze classes at run time.
• view objects at run time, for example, write a toString method for all classes.
• implement general array operation code.
• use the Method object to call the methods of the runtime class through the Method object.
• and inject JavaBean objects into SSM framework, etc

1, Class class

To use reflection, you must understand what Class is.
At runtime, the system always maintains a type ID called runtime for all objects. This information tracks the Class to which each object belongs. The Class that holds this information is called Class. The instance object of this Class can provide information about the corresponding Class itself, such as several construction methods, how many data fields there are, what behavior methods there are, etc.
Look at the code (exceptions need to be caught for the use of some methods in the coding process. I threw them all out for ease of reading):

1.  /** 
2.	 * Now there is a test class with data fields and behavior methods 
3.	 */  
4.	public class ReflectiveTest {  
5.	    private String name;  
6.	    private int data;  
7.	    public ReflectiveTest() {}  
8.	    public ReflectiveTest(String name, int data) {  
9.	        this.name = name;  
10.	        this.data = data; }  
11.	    public String getName() {  
12.	        return name;}  
13.	    public void setName(String name) {  
14.	        this.name = name; }  
15.	    public int getData() {  
16.	        return data;}  
17.	    public void setData(int data) {  
18.	        this.data = data;}  
19.	} 

In the main method:

20.	//Create an object for the test class  
21.	ReflectiveTest t = new ReflectiveTest();  
22.	/** 
23.	 * There are several methods to obtain Class instance objects: 
24.	 * 1.Is through the class object. getClass method 
25.	 * 2.Is through the class name. Class 
26.	 * 3.Through class. Forname,
27.  * If the class name is saved in a string and can be changed at run time, you can use this method to get it
28.	 * The third method may throw classnotfoundexception (without this class). I threw it directly here 
29.	 */  
30.	Class clazz = t.getClass();  
31.	Class clazz2 = ReflectiveTest.class;  
32.	Class clazz3 = Class.forName("ReflectiveTest");  
33.	//These Class instance objects retain all the information in the reflective test Class

Please note that a Class object actually represents a type, and this type may not necessarily be a kind. For example, int is not a Class, but int.class is an object of Class type.

The common methods of Class class are getName, which is used to return the Class name:

/** 
2.	 * A Class object will represent the properties of a particular Class. The most common Class method is getName(). This method will return the name of the Class 
3.	 * If the class is in a package, the package name will also appear as the class name (not shown here) 
4.	 */  
5.	System.out.println(clazz.getName());//Name of return class: ReflectiveTest

Another common method of Class class is newInstance() method, which can dynamically create a Class object according to the empty parameter Constructor of the runtime Class, or use the newlnstance method in the Constructor Class to call the corresponding parametric Constructor method:

1.	/** 
2.	 * A Class object will represent the properties of a particular Class. The most common Class method is getName(). This method will return the name of the Class 
3.	 * If the class is in a package, the package name will also appear as the class name (not shown here) 
4.	 */  
5.	System.out.println(clazz.getName());//Name of return class: ReflectiveTest  
6.	  
7.	/** 
8.	 * Class Common methods: newInstance(): call the null parameter constructor to create the corresponding class object 
9.	 * If you want to call a Constructor with parameters, you must first obtain the Constructor class object, and then call the corresponding newInstance method 
10.	 */  
11.	Object o = clazz.newInstance();//Nonparametric structure  
12.	//Returns a reflective test class Object (Object is the parent of all classes, so you can point to it with an Object class reference)  
13.	//Class.getConstructors() returns all constructor methods in the class in order, with subscripts starting from 0  
14.	Constructor[] constructor = clazz.getConstructors();  
15.	//Create a reflective test class object according to the parameter constructor, name="test1",data=1  
16.	Object test1 = constructor[1].newInstance("test1", 1);  

2, Using reflection to check the structure of classes

There are three classes Field, Method and Constructor in the Java reflection class library, which are used to describe the data Field, Method and Constructor of the class respectively. These three classes have a Method called getName, which is used to return the name of the corresponding class, as well as some commonly used methods. Look at the code:

1.	/** 
2.	 * Field,Method,Constructor Object acquisition and the use of some common methods 
3.	 */  
4.	//All data fields defined in the return class (including private fields) are not necessarily returned in the defined order
5.	Field[] fields = clazz.getDeclaredFields();
6.	//Returns all the methods defined in the class. The return order is not necessarily in the defined order
7.	Method[] methods = clazz.getDeclaredMethods();
8.	//Returns all construction methods defined in the class. The return order may not be in the defined order
9.	Constructor[] constructors = clazz.getConstructors();
10.	//The Field.getType method is used to return the Class object describing the type of the field  
11.	System.out.println(fields[0].getType());//Type name of the first data output and: class java.lang.String(String type)  
12.	  
13.	for (Method method : methods) {  
14.	    System.out.println(method.getReturnType());  
15.	    //This Method returns the generic parameters of the Method object. If there is no generic, it returns an array of length 0  
16.	    //There are no generic methods in this class, so they are all arrays of length 0  
17.	    TypeVariable[] typeParameters = method.getTypeParameters();  
18.	    System.out.println(typeParameters.length);  
19.	    for (int j = 0;j < typeParameters.length;j++){  
20.	        System.out.print(typeParameters[j].getName()+" ");  
21.	    }  
22.	    System.out.println();  
23.	}  
24.	  
25.	/** 
26.	 * These three classes also have a method called getModifiers, which will return an integer value, 
27.	 * Use different bit switches to describe the use of modifiers such as public and static 
28.	 * For example, you can use isPublic, isPrivate, or isFinal in the Modifier class 
29.	 * Determine whether the method or constructor is public, private, or final. All we need to do is call Modifier 
30.	 * Class and analyze the returned integer value. In addition, you can use the Modifier.toString method to 
31.	 * The modifier prints out 
32.	 */  
33.	System.out.println(fields[0].getModifiers());  
34.	System.out.println(Modifier.isPrivate(fields[0].getModifiers()));  
35.	System.out.println(methods[0].getModifiers());  
36.	System.out.println(Modifier.isPublic(methods[0].getModifiers()));

When obtaining class information through methods such as Field or Method, if it is a private property or Method in the class, the private methods and properties in the class can be used only after calling the Method through setAccessible Method, such as x. setAccessible(true), otherwise an error will be reported.

3, Call any method

In the above discussion, we know that Method can get the methods defined in the class, but what if we call these methods in the class? We can use the invoke function provided by the Method class to call the corresponding Method.
The Invoke function signature is as follows:
Object invoke(Object obj, Object... args)
The first parameter obj is an implicit parameter, and the other objects (variable length parameter args) provide explicit parameters. (in versions before Java SE 5.0, an object array must be passed, and null if there are no explicit parameters). For static methods, the first parameter can be ignored, that is, it can be set to null.

1.	//Call the setName method to reset the name  
2.	methods[2].invoke(t,"test2");  
3.	System.out.println(t.getName());//Output test2

summary

This article only records my personal opinions when I first learned reflection. For some methods and concepts, I have to refer to api documents and other materials.

Topics: Java reflection