A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

设置为私有的变量,并且设置为不可到达,为什么在我的电脑上显示出现结果。
有兴趣的同学拿去试验一下,看看是否与我电脑配置有关系。
我用的是jdk 1.7版本。
public class InstanceDemo {
        public int x;
        private int y;
        public InstanceDemo(int x,int y) {
                super();
                this.x = x;
                this.y = y;
        }
        public static void main(String[] args)throws Exception{
//                Field y = InstanceDemo.class.getField("x");
//                Field x = InstanceDemo.class.getDeclaredField("y");
                InstanceDemo i = new InstanceDemo(5,10);
                Field fieldY = i.getClass().getDeclaredField("y");
                fieldY.setAccessible(false);
                System.out.println(fieldY.get(i));
        }
}

捕获.PNG (704 Bytes, 下载次数: 3)

捕获.PNG

6 个回复

倒序浏览
老师那边教学显示的是不可到达。
回复 使用道具 举报
白月留梦 来自手机 中级黑马 2015-6-7 20:59:15
藤椅
你fieldY对应的是‘x`的值    而你的x的值是public修饰的    所以可以访问到
回复 使用道具 举报
那是因为,你把主函数和私有的y放在同一个类中了,
在同一个类中,私有成员是可以访问的,你把它们分到不同类中就有区别了。
代码在下边,你把false改为true就可以执行了
  1. import java.lang.reflect.Field;

  2. class InstanceDemo  {
  3.         public int x;
  4.         private int y;

  5.         public InstanceDemo (int x, int y) {
  6.                 super();
  7.                 this.x = x;
  8.                 this.y = y;
  9.         }
  10. }

  11. public class Demo {
  12.        
  13.         public int x;
  14.         private int y;

  15.         public Demo(int x, int y) {
  16.                 super();
  17.                 this.x = x;
  18.                 this.y = y;
  19.         }

  20.         public static void main(String[] args) throws Exception {
  21.                 // Field y = InstanceDemo.class.getField("x");
  22.                 // Field x = InstanceDemo.class.getDeclaredField("y");
  23.                 InstanceDemo  i = new InstanceDemo (5, 10);
  24.                 Field fieldY = i.getClass().getDeclaredField("y");
  25.                 fieldY.setAccessible(false);
  26.                 System.out.println(fieldY.get(i));
  27.         }
  28. }
复制代码
回复 使用道具 举报
嘎路的米 发表于 2015-6-7 21:13
那是因为,你把主函数和私有的y放在同一个类中了,
在同一个类中,私有成员是可以访问的,你把它们分到不同 ...

有道理。
Thank you so much。:hug:
回复 使用道具 举报
主函数和上面的在一个类,类里面可以直接访问
回复 使用道具 举报
过来凑热闹的!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马