您的位置:首页 > 编程语言 > Java开发

java反射访问私有成员变量

2013-06-24 08:50 344 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: