Copy property with different names between beans using BeanUtils

删除回忆录丶 提交于 2019-12-10 17:50:02

问题


I would like to copy the property values from Class A to Class B with BeanUtils which has same fields but with different names. Is it possible to provide a map of property name to differentName, age to differentAge etc., and achieve the copying? I am interested to know if this is possible by any means using only Apache Commons utilities (not any other tools).

class ClassA{
    private String name;
    private Integer age;
    ... // Setter and Getter methods
} 

class ClassB{
    private String differentName;
    private Integer differentAge;
    ... // Setter and Getter methods for the private fields
}

回答1:


Apache Commons BeanUtils has method the method populate(Object bean, Map properties) accepts a map to populate the Bean with key value pairs.

NOTE: I just saw the limitation on Apache-Commons - but it may still be useful for other people and as far as I am concerned the better solution.

Use Dozer when the names match it will automatically copy the values. Or as in your case you can specify source and target Members in an xml mapping file.



来源:https://stackoverflow.com/questions/12970475/copy-property-with-different-names-between-beans-using-beanutils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!