黑马程序员技术交流社区

标题: IntroSpector [打印本页]

作者: 杨曾荣    时间: 2012-2-22 15:04
标题: IntroSpector
看一下定义了两个类的代码,解决一个问题
public class ReflectPoint {
        private int x;
        private int y;
       
        public ReflectPoint(){}
        public ReflectPoint(int x, int y) {
                super();
                this.x = x;
                this.y = y;
        }
下面还有x、y的get、set方法

public class IntroSpectorTest {
        public static void main(String[] args) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
               
                ReflectPoint rp=new ReflectPoint(4,8);
                String propertyName="x";
               
                PropertyDescriptor pd=new PropertyDescriptor(propertyName, rp.getClass());
                Method methodGetX=pd.getReadMethod();
                Object retVal=methodGetX.invoke(rp);
               
                System.out.println(retVal);

String propertyName="x";这里就直接给它x的值了,x的值是从上面这个类ReflectPoint的成员变量,当我们不知道ReflectPoint的成员变量的时候,这时候我们该什么给
这个String propertyName=??赋值呢,也就是说不直接给定一个x的值,我们还能通过另一种方式来赋值呢?
作者: 欧阳博    时间: 2012-2-22 15:29
本帖最后由 oyb1988 于 2012-2-22 16:00 编辑

你是想问在不知道类有什么属性的情况下获得它的属性值,然后再赋值给别人吗?
  1. ReflectPoint rp=new ReflectPoint(4,8);
  2. Field[] fie = rp.getClass().getDeclaredFields();
  3. for(int i=0;i<fie.length;i++)
  4. {
  5.                fie[i].setAccessible(true);  //如果上面类的属性是私有的,必须设置暴力反射
  6.         System.out.println(fie[i]);  //这里可以得到rp对象所有的属性
  7.          System.out.println(fie[i].get(rp));   //打印属性值
  8. }
复制代码





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