可以通过反射获取字段的值,具体步骤如下:
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
}
}