可以通過反射獲取字段的值,具體步驟如下:
Class clazz = YourClass.class;
Field field = clazz.getDeclaredField("fieldName");
field.setAccessible(true);
Object value = field.get(instance);
其中,fieldName為字段的名稱,instance為包含該字段的對象實例。
示例代碼如下:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Person person = new Person("Alice", 25);
Class clazz = Person.class;
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
Object value = field.get(person);
System.out.println(value); // 輸出:Alice
}
}