使用BeanUtils在bean之间复制具有不同名称的属性 [英] Copy property with different names between beans using BeanUtils
问题描述
我想使用具有相同字段但名称不同的BeanUtils将属性值从A类复制到B类.是否可以提供一个属性名称映射到differentName,年龄映射到differentAge等,并实现复制?我很想知道是否可以仅通过Apache Commons实用程序(而不是任何其他工具)以任何方式实现.
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
}
推荐答案
Apache Commons BeanUtils has method the method populate(Object bean, Map properties) accepts a map to populate the Bean with key value pairs.
注意:我刚刚看到了Apache-Commons的局限性-但它可能对其他人还是有用的,就我而言,更好的解决方案.
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.
在名称匹配时使用推土机,它将自动复制值.或者根据您的情况,您可以在xml映射文件中指定源成员和目标成员.
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.
这篇关于使用BeanUtils在bean之间复制具有不同名称的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!