3.12. Cloning a Bean

Problem

You need to clone a bean.

Solution

Use BeanUtils.cloneBean() . This method creates a new instance of a bean with the default constructor, and it copies every property to the new bean instance. The following instance creates a cloned instance of a Book object:

import org.apache.commons.beanutils.BeanUtils;

Book book1 = new Book( );
book1.setName( "Count of Monte Cristo" );

Book book2 = (Book) BeanUtils.cloneBean( book1 );

Discussion

cloneBean( ) instantiates a new instance of the bean to be cloned and calls BeanUtils.copyProperties( ) to transfer all readable bean properties to the newly instantiated bean. The following code demonstrates the steps that cloneBean( ) is taking to clone an instance of a bean:

Book book1 = new Book( );
book1.setName( "Practical C Programming" );

Book book2 = book1.getClass( ).newInstance( );
               PropertyUtils.copyProperties( book2, book1 );

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.