Java reflection-access to member variables

reflection

Through the Java reflection mechanism, the description of the Java object that has been loaded into the JVM can be accessed in the program, and the function of accessing, detecting and modifying the information describing the Java object itself can be realized. Through reflection, you can access constructors, member variables, and member methods.

Access to the constructor: Java reflection-access to the constructor
access to the member method: Java reflection-access to the member method

Access member variables

Use the Field object to manipulate the corresponding member variables.
Insert picture description here
Common methods of the Field class:

method Description
getName() Get the name of a member variable
getType() Obtain the class object representing the type of the member variable
get(Object obj) Get the value of the member variable in the specified object obj, the return value is Object type
set(Object obj, Object value) Set the value of the member variable in the specified object obj to value
getInt (Object obj) Get the value of a member variable of type int in the specified object obj
setInt(Object obj, int i) Set the value of the member variable of type int in the specified object obj to i
getFloat((Object obj)) Get the value of a member variable of type float in the specified object obj
setFloat(Object obj, float f) Set the value of the member variable of type float in the specified object obj to f
getBoolean(Object obj) Get the value of a member variable of type Boolean in the specified object obj
setBoolean(Object obj, boolean z) Set the value of the member variable of type Boolean in the specified object obj to z
setAccessible(boolean flag) This method can set whether to ignore permission restrictions and directly access member variables with private permissions such as private
getModifiers() Get an integer that can parse out the modifier used by the member variable

The return value of the getModifiers() method is the modifier information represented. A series of static methods for parsing are provided in this class. You can not only check whether it is modified by the specified modifier, but also get all of them in the form of a string Modifier.

Common analytical methods in the Modifier class:

Static method Description
isPublic(int mod) Check whether it is modified by the public modifier, if it is true, otherwise it returns false
isProtected(int mod) Check whether it is modified by the protected modifier, if it is true, otherwise it returns false
isPrivate(int mod) Check whether it is modified by the private modifier, if it is true, otherwise it returns false
isStatic(int mod) Check whether it is modified by the static modifier, if it is true, otherwise it returns false
isFinal (int mod) Check whether it is modified by the Final modifier, if it is true, otherwise it returns false
toString(int mod) Return all modifiers as a string

Get and modify the value of a member variable:
Insert picture description here
first create a Study class, declare three different types of member variables with different modifiers in this class, and assign them.

public class Study {
    
    
	public int id = 1;
	public String name = "反射";
	private double price = 3.1315;

}

Then reflect these three variables in another class Study2.

public class Study2 {
    
    

	public static void main(String[] args) {
    
    
		try {
    
    
			Class c = Class.forName("study.czm.Study");// 创建class对象
			Field fi[] = c.getDeclaredFields();// 获取所有成员变量
			for (Field f : fi) {
    
    
				System.out.print(Modifier.toString(f.getModifiers()) + " ");// 获取成员变量修饰符
				System.out.print(f.getType());// 获取成员变量类型
				System.out.println();
			}
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		}

	}
}

Successfully obtained the modifier and type of the member variable.
Insert picture description here
Note: The String type has obtained the complete name, which needs to be simplified. Add a method getSimpleName() to the line of code that obtains the member variable type.

System.out.print(f.getType().getSimpleName());// 获取成员变量类型

Insert picture description here
Get the value of the member variable name through reflection

//创建对象
			Constructor cs = c.getConstructor();
			Study s = (Study) cs.newInstance();//获取Study对象
			Field f1 = c.getDeclaredField("name");//指定获取name的成员变量属性
			System.out.println("name的值:" + f1.get(s));//获取name成员变量的值

Insert picture description here
Modify the value in getDeclaredField() to get the value of different variables and get the value of the member variable id:

//创建对象
			Constructor cs = c.getConstructor();
			Study s = (Study) cs.newInstance();//获取Study对象
			Field f1 = c.getDeclaredField("id");//指定获取id的成员变量属性
			System.out.println("id的值:" + f1.get(s));//获取id成员变量的值

Insert picture description here
The modifier of the double type is private, so permission is required

//创建对象
			Constructor cs = c.getConstructor();
			Study s = (Study) cs.newInstance();//获取Study对象
			Field f1 = c.getDeclaredField("price");//指定获取price的成员变量属性
			f1.setAccessible(true);//获取访问权限
			System.out.println("price的值:" + f1.get(s));//获取price成员变量的值

Insert picture description here
In addition to obtaining, we can also modify these values, take id as an example

//创建对象
			Constructor cs = c.getConstructor();
			Study s = (Study) cs.newInstance();//获取Study对象
			Field f1 = c.getDeclaredField("id");//指定获取id的成员变量属性
			System.out.println("id本来的的值:" + f1.get(s));//获取id成员变量的值
			f1.set(s, 100);//修改id的值
			System.out.println("id修改后的值:" + f1.get(s));//输出id的值

Insert picture description here
Complete code of Study2 category:

public class Study2 {
    
    

	public static void main(String[] args) {
    
    
		try {
    
    
			Class c = Class.forName("study.czm.Study");// 创建class对象
			Field fi[] = c.getDeclaredFields();// 获取所有成员变量
			for (Field f : fi) {
    
    
				System.out.print(Modifier.toString(f.getModifiers()) + " ");// 获取成员变量修饰符
				System.out.print(f.getType().getSimpleName() + " ");// 获取成员变量类型
				System.out.print(f.getName());// 获取成员变量名称
				System.out.println();
			}

			// 创建对象
			Constructor cs1 = c.getConstructor();
			Study s = (Study) cs1.newInstance();// 获取Study对象
			Field f1 = c.getDeclaredField("id");// 指定获取id的成员变量属性
			System.out.println("id本来的的值:" + f1.get(s));// 获取id成员变量的值
			f1.set(s, 100);// 修改id的值
			System.out.println("id修改后的值:" + f1.get(s));// 输出id的值

			// 创建对象
			Constructor cs2 = c.getConstructor();
			s = (Study) cs2.newInstance();// 获取Study对象
			Field f2 = c.getDeclaredField("name");// 指定获取name的成员变量属性
			System.out.println("name的值:" + f2.get(s));// 获取name成员变量的值

			// 创建对象
			Constructor cs3 = c.getConstructor();
			s = (Study) cs3.newInstance();// 获取Study对象
			Field f3 = c.getDeclaredField("price");// 指定获取price的成员变量属性
			f3.setAccessible(true);// 获取访问权限
			System.out.println("price的值:" + f3.get(s));// 获取price成员变量的值

		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
    
    
			e.printStackTrace();
		} catch (SecurityException e) {
    
    
			e.printStackTrace();
		} catch (InstantiationException e) {
    
    
			e.printStackTrace();
		} catch (IllegalAccessException e) {
    
    
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
    
    
			e.printStackTrace();
		} catch (InvocationTargetException e) {
    
    
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
    
    
			e.printStackTrace();
		}

	}
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/javanofa/article/details/104751955