概述
public class StudentDemo {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchFieldException, SecurityException {
Student clazz=Student.class.newInstance();
Field[] fields = Student.class.getFields();
System.out.println("Size:"+fields.length);
for (Field field : fields) {
System.out.println("field:"+field.getName());
}
Field[] declaredFields = Student.class.getDeclaredFields();
Field field = Student.class.getDeclaredField("age");
//取消访问检查
field.setAccessible(true);
Object oldStu = field.get(clazz);
System.out.println("oldStu:"+oldStu);
field.set(clazz, 45);
System.out.println("->");
Object newStu = field.get(clazz);
System.out.println("newStu:"+newStu);
}
}
Student类:
public class Student {
private int age=12;
public String name;
}
获取私有变量与私有方法同理。
最后
以上就是畅快魔镜为你收集整理的Java通过反射获取对象的私有变量的全部内容,希望文章能够帮你解决Java通过反射获取对象的私有变量所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复