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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© §傻、才乖 中级黑马   /  2013-12-20 16:06  /  1205 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package cn.itcast.day1;
public class ReflectPoint {
private int x;
public int y = 10;

public ReflectPoint(int x, int y) {
  super();
  this.x = x;
  this.y = y;
}

}


ReflectPoint pt = new ReflectPoint(3, 5);
  String variableName = "y";
  Field field = getField(pt, variableName);
  System.out.println(field.get(pt));
这样只能获取到对象初始化之后 y的值
有没有方法获取到类上y的值

评分

参与人数 1技术分 +1 收起 理由
乔兵 + 1

查看全部评分

3 个回复

倒序浏览
这个javaBean类用内省取出他的值
  1. public class NeiXing
  2. {
  3.     public static void main(String[] args) throws Exception
  4.     {
  5.             PropertyDemo pr=new PropertyDemo();
  6.             BeanInfo bean=Introspector.getBeanInfo(PropertyDemo.class);
  7.             PropertyDescriptor[] property=bean.getPropertyDescriptors();
  8.            
  9.             for(PropertyDescriptor p:property)
  10.             {  
  11.                     Class clazz=p.getPropertyType();
  12.                     if(clazz!=Class.class)
  13.                     {
  14.                     Method methodr=p.getReadMethod();
  15.                     System.out.println(p.getName()+"="+methodr.invoke(pr));
  16.                     }
  17.             }
  18.     }
  19. }

  20. class PropertyDemo
  21. {
  22.     private static  int x=1;
  23.     private int y=2;
  24.         public int getX() {
  25.                 return x;
  26.         }
  27.         public void setX(int x) {
  28.                 this.x = x;
  29.         }
  30.         public int getY() {
  31.                 return y;
  32.         }
  33.         public void setY(int y) {
  34.                 this.y = y;
  35.         }
  36.        
  37. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
乔兵 + 1

查看全部评分

回复 使用道具 举报
末末 发表于 2013-12-20 16:31
这个javaBean类用内省取出他的值

我不想把它当javabean能不能取出类中y的值
回复 使用道具 举报
§傻、才乖 发表于 2013-12-20 16:40
我不想把它当javabean能不能取出类中y的值
  1. public class FanShe
  2. {
  3.         public static void main(String[] args) throws Exception, Exception
  4.         {
  5.                 fsDemo fs=new fsDemo();
  6.                 Class clazzfs=fs.getClass();
  7.                 Field[] fields=clazzfs.getDeclaredFields();
  8.                 for(Field field : fields)
  9.                 {
  10.                         field.setAccessible(true);
  11.                         Object o=field.get(fs);
  12.                         System.out.println(field.getName()+"="+o.toString());
  13.                 }
  14.         }

  15. }

  16. class fsDemo
  17. {
  18.     private int x=1;
  19.     public int y=2;
  20. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马