3.11. Copying Bean Properties

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.

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.

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 );

See Also

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.78.83