如何将所有属性从父级复制到子bean?

时间:2018-01-30 12:43:29

标签: java apache-commons apache-commons-beanutils

我有一个父子层次结构bean,并希望将所有属性从父对象复制到子对象。

以为我可以使用apache commons BeanUtils,但失败了。但为什么呢?

public class ParentChildCopyTest {
    class Person {
        String name;
    }

    class Child extends Person {
        private String birthday;
    }

    @Test
    public void test() throws Exception {
        Person p = new Person();
        p.name = "Dummy";

        Child c = new Child();
        org.apache.commons.beanutils.BeanUtils.copyProperties(c, p);
        assertEquals(p.name, c.name); //this FAILS
    }
}

旁注:当然,我的真实世界对象要复杂得多。我正在寻找一种方法必须手动复制所有属性是getter / setter(特别是因为我不想在这种特定情况下添加getter / setter)。

1 个答案:

答案 0 :(得分:1)

BeanUtils需要公共getter和setter,它不会对私有字段做任何事情。

但你可以使用反射,例如使用Springs ReflectionUtils。

此库允许您读写私有字段。 一个例子 : https://www.intertech.com/Blog/using-springs-reflectionutils-to-access-private-fields/