从一个对象中复制属性

2020-04-20  本文已影响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);
                    }
                }
            }
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读