美文网首页
从一个对象中复制属性

从一个对象中复制属性

作者: 靳兆鲁 | 来源:发表于2020-04-20 11:21 被阅读0次
    class Coder {
    
        private String name = "";
        private int age = 0;
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public void cloneFrom(Coder coder) {
            Field[] declaredFieldsFrom = coder.getClass().getDeclaredFields();
            Field[] declaredFields = getClass().getDeclaredFields();
            for (final Field declaredFieldFrom : declaredFieldsFrom) {
                for (final Field declaredField : declaredFields) {
                    if (declaredFieldFrom.getName().equals(declaredField.getName())) {
                        try {
                            declaredField.set(this, declaredFieldFrom.get(coder));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                            declaredField.setAccessible(true);
                            declaredFieldFrom.setAccessible(true);
                            try {
                                declaredField.set(this, declaredFieldFrom.get(coder));
                            } catch (IllegalAccessException ex) {
                                ex.printStackTrace();
                            }
    
                            declaredField.setAccessible(false);
                            declaredFieldFrom.setAccessible(false);
                        }
                    }
                }
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:从一个对象中复制属性

          本文链接:https://www.haomeiwen.com/subject/felrihtx.html