public class ReflectTest {
private volatile String name = "before";
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
ReflectTest test = new ReflectTest();
try {
System.out.println(getValue(test, "name"));
test.setName("after");
System.out.println(getValue(test, "name"));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public static Object getValue(Object instance, String fieldName) throws IllegalAccessException,
NoSuchFieldException {
Field field = getField(instance.getClass(), fieldName);
// 参数值为true,禁用访问控制检查
field.setAccessible(true);
return field.get(instance);
}
public static Field getField(Class thisClass, String fieldName) throws NoSuchFieldException {
if (fieldName == null) {
throw new NoSuchFieldException("Error field !");
}
Field field = thisClass.getDeclaredField(fieldName);
return field;
}
}
打印结果
before
after
本文通过一个Java示例展示了如何使用反射机制获取并修改私有字段的值。具体包括通过Class对象获取Field对象,设置其可访问性,并读取实例变量。
207

被折叠的 条评论
为什么被折叠?



