Java Reflection: Get Object Attribute Values
In Java, the reflection mechanism can be used to access the properties of an object. The specific steps are as follows:
- To obtain the Class object of an object: use the getClass() method to retrieve the Class object of an object.
- To access an object’s properties, you can use the getDeclaredField() method or the getField() method. The difference between them is that the former can access properties with all access modifiers, while the latter can only access properties with the public modifier.
- Set the access permission of the attribute: if the attribute is private, it needs to be set as accessible by using the setAccessible(true) method.
- Retrieve the value of an attribute: Use the get() method to retrieve the value of an attribute.
Below is an example code:
public class Main {
public static void main(String[] args) throws Exception {
// 创建对象
Person person = new Person("John", 25);
// 获取对象的Class对象
Class<?> clazz = person.getClass();
// 获取属性名为name的属性
Field nameField = clazz.getDeclaredField("name");
// 设置属性的访问权限
nameField.setAccessible(true);
// 获取属性的值
String name = (String) nameField.get(person);
System.out.println("name: " + name);
// 获取属性名为age的属性
Field ageField = clazz.getDeclaredField("age");
// 设置属性的访问权限
ageField.setAccessible(true);
// 获取属性的值
int age = (int) ageField.get(person);
System.out.println("age: " + age);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
The output is:
name: John
age: 25