Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy property with different names between beans using BeanUtils

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
}
like image 689
Cid Avatar asked Oct 19 '12 08:10

Cid


People also ask

How do you copy properties of beans?

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.

Is it good to use BeanUtils copyProperties?

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.

What is BeanUtils copyProperties () Java?

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.

What is Commons BeanUtils used for?

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.


1 Answers

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.

like image 164
dngfng Avatar answered Sep 24 '22 19:09

dngfng