黑马程序员技术交流社区

标题: 关于反射:私有变量设置为不可访问时依然有访问到... [打印本页]

作者: YongBao_Summer    时间: 2015-6-7 20:37
标题: 关于反射:私有变量设置为不可访问时依然有访问到...
设置为私有的变量,并且设置为不可到达,为什么在我的电脑上显示出现结果。
有兴趣的同学拿去试验一下,看看是否与我电脑配置有关系。
我用的是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

作者: YongBao_Summer    时间: 2015-6-7 20:38
老师那边教学显示的是不可到达。
作者: 白月留梦    时间: 2015-6-7 20:59
你fieldY对应的是‘x`的值    而你的x的值是public修饰的    所以可以访问到
作者: 嘎路的米    时间: 2015-6-7 21:13
那是因为,你把主函数和私有的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. }
复制代码

作者: YongBao_Summer    时间: 2015-6-7 22:57
嘎路的米 发表于 2015-6-7 21:13
那是因为,你把主函数和私有的y放在同一个类中了,
在同一个类中,私有成员是可以访问的,你把它们分到不同 ...

有道理。
Thank you so much。:hug:
作者: 郭.威    时间: 2015-6-8 00:15
主函数和上面的在一个类,类里面可以直接访问
作者: Enhon1992    时间: 2015-6-8 08:53
过来凑热闹的!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2