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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© DOOR 中级黑马   /  2014-1-9 14:32  /  887 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 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. }
复制代码
老报错,求解
还有代码上没写的,暴力反射有什么用?这个东西打破了封装性,有什么存在价值?

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

3 个回复

倒序浏览
本帖最后由 小悠久 于 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);
                        }                        
        }
}
反射能够获取到类的私有构造函数,成员变量和方法,并对其进行操作。

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

回复 使用道具 举报
根据你的代码我运行了一下!抛异常后没有错呀,你【抛出异常试试。
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)访问私有变量

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

回复 使用道具 举报
谢谢几位,问题解决了,因为我一看Field是lang包里的就没有导包,lang包不是自动加载的吗?
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马