Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

3.11. Copying Bean Properties

3.11.1. Problem

You have two instances of a bean, and you need to copy the properties of one bean to another instance of the same class.

3.11.2. Solution

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.apache.commons.beanutils.PropertyUtils;
Book book = new Book( );
book.setName( "Prelude to Foundation" );
book.setAuthorName( "Asimov" );
Book destinationBook = new Book( );
PropertyUtils.copyProperties( destinationBook, book );

After executing this code, destinationBook.getName() should return "Prelude to Foundation," and destinationBook.getAuthorName( ) should return "Asimov"; the name and authorName properties of book were both copied to destinationBook.

3.11.3. Discussion

PropertyUtils.copyProperties( ) retrieves the values of all properties from a source instance of a bean, assigning the retrieved values to a matching property on a destination instance. If the Book bean in the previous example had an author property of type Author, copyProperties( ) would have assigned the same reference object to the destinationBook. In other words, copyProperties( ) does not clone the values of the bean properties. The following example demonstrates this explicitly:

Author author = new Author( );
author.setName( "Zinsser" );
Book book = new Book( );
book.setName( "On Writing Well" );
book.setAuthor( author );
Book destinationBook = new Book( );
PropertyUtils.copyProperties( destinationBook, book );
// At this point book and destinationBook have the same author object
if( book.getAuthor( ) == destinationBook.getAuthor( ) ) {
    system.out.println( "Author objects identical" );
}

The author properties of these two objects are now identical references to the same instance of the Author class. copyProperties( ) does not clone the values of bean properties.

copyProperties( ) can also copy the contents of a Map to a bean if the keys of a Map correspond to names of simple bean properties on the destination bean:

Map mapProps = new HashMap( );
mapProps.put( "name", "The Art of Computer Programming" );
mapProps.put( "author", "Knuth" );
Book destinationBook = new Book( );
PropertyUtils.copyProperties( destinationBook, mapProps );

3.11.4. See Also

If you need to clone a bean, take a look at Recipe 3.12


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.