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 ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.