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
}
Use PropertyUtils. copyProperties() to copy the properties from one bean to another. The first parameter is the destination bean, and the second parameter is the bean to copy properties from: import org.
If they're already immutable then a reference is as good as a copy. BeanUtils. copyProperties is often a less intrusive way of copying without having to alter your classes to be supported, and it offers some unique flexibility in compositing objects. That said, copyProperties is not always one-size-fits-all.
BeanUtils class provides a copyProperties method that copies the properties of source object to target object where the property name is same in both objects.
Commons BeanUtils is a collection of utilities that makes working with beans and bean properties much easier. This project contains utilities that allow one to retrieve a bean property by name, sort beans by a property, translate beans to maps, and more.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With