Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

3.12. Cloning a Bean

3.12.1. Problem

You need to clone a bean.

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

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

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.