How to use Java reflection to retrieve the value of a p…
To retrieve the value of a property using Java reflection, you can follow these steps:
- To obtain the Class object: first, you need to acquire the Class object of the class you want to manipulate. You can use the Class.forName() method by passing the fully qualified name of the class to obtain the Class object, or use the .class syntax.
- Instantiating an object: If the attribute that needs to be accessed is an instance variable, the object of that class must be instantiated first.
- Fetch the Field object: Use the Class.getDeclaredField() method passing in the attribute name to obtain the Field object.
- To access the property, you need to first call Field.setAccessible(true) to set the accessibility.
- Accessing property values: Use the Field.get() method to retrieve the property value by passing in the object instance (if it is an instance variable) or null value (if it is a static variable).
Here is an example code demonstrating how to use Java reflection to retrieve property values.
import java.lang.reflect.Field;
public class ReflectionExample {
private String name = "John";
public int age = 25;
public static void main(String[] args) throws Exception {
// 获取Class对象
Class<?> clazz = ReflectionExample.class;
// 实例化对象
ReflectionExample obj = (ReflectionExample) clazz.newInstance();
// 获取属性Field对象
Field nameField = clazz.getDeclaredField("name");
Field ageField = clazz.getField("age");
// 设置可访问性
nameField.setAccessible(true);
// 获取属性值
String nameValue = (String) nameField.get(obj);
int ageValue = (int) ageField.get(null);
// 打印属性值
System.out.println("name: " + nameValue);
System.out.println("age: " + ageValue);
}
}
Note: Here it is assumed that the property is accessible. If the property to be accessed is private, the accessibility needs to be set. Additionally, if the property is a static variable, pass a null value when retrieving the property value.