Copy values from one Java object to another

If you want to copy values from one object instance to another that have (some or all) properties of the same name you can use the BeanUtils class in the Apache Commons Beanutils library to easily do just that. The BeanUtils method has a static method called copyProperties that takes two objects as parameters. The first is the destination object and the second is the origin object from which to copy the values. The method checks what properties are present in both objects and copy the values from the origin to the destination.

In this example we copy values from an instance of a Car class to an instance of a Motorcycle class. Both classes inherit from Vehicle, and the Car class has one extra property that is not present in the Motorcycle class.




Below is the code to copy properties from the Car instance to the Motorcycle instance. First we create the Car instance and populate its properties. Then we call the describe method of the BeanUtils class to get a Map with key/value pairs for that instance so we can iterate over its properties and print them out. After that it’s time to copy the values to an instance of Motorcycle using the copyProperties method of the BeanUtils class. Finally we do the same with the motorcycle instance, namely call the describe method and iterate over its properties and print them out.

The output from the code above looks like this:

Search for more Java info on this site here:
Custom Search

Please type any questions here.