黑马程序员技术交流社区

标题: 可将obj对象中名为propertyName的属性的... [打印本页]

作者: xingzjx    时间: 2015-3-17 17:44
标题: 可将obj对象中名为propertyName的属性的...
public class Test2 {
       
        public static void main(String[] args) {
                Point p = new Point();
                p.setX(1);
                p.setY(2);
                System.out.println("原始的p:"+p);
                setProperty(p, "x", 5);
                System.out.println("设值的p:"+p);
        }

        /**
         * 给某个对象的属性设置某个值,属性名为propertyName,值是value,设置的对象是obj
         * @param obj
         * @param propertyName
         * @param value
         */
        public static void setProperty(Object obj, String propertyName, Object value) {
                try {
                        // 获取属性对象Field
                        Field field = obj.getClass().getDeclaredField(propertyName);
                        // 设置可以访问
                        field.setAccessible(true);
                        // 设值
                        field.set(obj, value);
                } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("修改失败!");
                }
               
        }

}

class Point {
        private int x;
        private int y;
       

        public int getX() {
                return x;
        }

        public void setX(int x) {
                this.x = x;
        }

        public int getY() {
                return y;
        }

        public void setY(int y) {
                this.y = y;
        }

        @Override
        public String toString() {
                return "x = "+x+", y = "+y;
        }
       
       
}


作者: lwj123    时间: 2015-3-17 19:11
这是反射那一块的知识吧
作者: xingzjx    时间: 2015-3-17 20:33
en对。。




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