黑马程序员技术交流社区

标题: 反射代码问题 [打印本页]

作者: DOOR    时间: 2014-1-9 14:32
标题: 反射代码问题
本帖最后由 DOOR 于 2014-1-16 00:39 编辑

  1. class ReflectPoint
  2. {
  3.         private int x;
  4.         public int y;
  5.         public ReflectPoint(int x,int y)
  6.         {
  7.                 this.x = x;
  8.                 this.y = y;
  9.         }
  10. }

  11. class Demo0707
  12. {
  13.         public static void main(String[] args)
  14.         {
  15.                 ReflectPoint rp = new ReflectPoint(3,5);
  16.                 Field fieldY = rp.getClass().getField("y");
  17.                
  18.                 System.out.println(fieldY.get(rp));
  19.         }
  20. }
复制代码
老报错,求解
还有代码上没写的,暴力反射有什么用?这个东西打破了封装性,有什么存在价值?

作者: 小悠久    时间: 2014-1-9 14:48
本帖最后由 小悠久 于 2014-1-9 14:49 编辑

import java.lang.reflect.Field;


class ReflectPoint

{
        private int x;
        public int y;
        public ReflectPoint(int x,int y)

        {
                this.x = x;
                this.y = y;
        }
}

class Test1

{
        public static void main(String[] args)

        
        {
              try{
                ReflectPoint rp = new ReflectPoint(3,5);
                Field fieldY =  rp.getClass().getField("y");   
                  System.out.println(fieldY.get(rp));
              }//没有捕获异常
                   catch (Exception e) {
           // TODO: handle exception
                      System.out.println(e);
                        }                        
        }
}
反射能够获取到类的私有构造函数,成员变量和方法,并对其进行操作。
作者: IT人    时间: 2014-1-9 14:55
根据你的代码我运行了一下!抛异常后没有错呀,你【抛出异常试试。
public class ReflectPoint {
          private int x;
      public int y;
      public ReflectPoint(int x,int y)
      {
              this.x = x;
              this.y = y;
      }

}
import java.lang.reflect.Field;

public class ReflectText {

        public static void main(String[] args)throws Exception {
                // TODO Auto-generated method stub
                ReflectPoint rp = new ReflectPoint(3,5);
        Field fieldY = rp.getClass().getField("y");
        
        System.out.println(fieldY.get(rp));

        }
}
下边是暴力反射的代码:
Field filedX = pt1.getClass().getDclaredField("x");
//通过setAccessible(true)方法来让成员变量x是可以访问的
fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1))
暴力反射就是通过fieldX.setAccessible(true)访问私有变量
作者: DOOR    时间: 2014-1-9 15:15
谢谢几位,问题解决了,因为我一看Field是lang包里的就没有导包,lang包不是自动加载的吗?




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