可以通过反射获取字段的值,具体步骤如下:
- 获取类的Class对象
Class clazz = YourClass.class;
- 获取字段对象
Field field = clazz.getDeclaredField("fieldName");
- 设置字段可访问
field.setAccessible(true);
- 获取字段的值
Object value = https://www.yisu.com/ask/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 = https://www.yisu.com/ask/field.get(person);>