9

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
}
Cid
  • 1,453
  • 1
  • 18
  • 37

1 Answers1

4

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.

dngfng
  • 1,923
  • 17
  • 34
  • But the populate will still need the same field name. How will I map 'age' property to 'differentAge' property? – Cid Oct 19 '12 at 11:19
  • As you can read in the linked API: "properties - Map keyed by property name, with the corresponding (String or String[]) value(s) to be set". The key will have to be "differentAge" and the value 20 or what ever... You will have to map the values somewhere either this way or by using Dozer and xml mappings. – dngfng Oct 19 '12 at 11:51
  • You are welcome, has been a long time since you posted the question :) – dngfng Nov 19 '14 at 18:10