繁体   English   中英

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

[英]How to copy all properties from parent to child bean?

我有一个父子层次结构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在这种特殊情况下)。

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

但是您可以使用反射,例如以Springs ReflectionUtils为例。

该库允许您读取和写入私有字段。 例如: https : //www.intertech.com/Blog/using-springs-reflectionutils-to-access-private-fields/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM