Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

3.13. Setting a Bean Property

3.13.1. Problem

You need to set a simple, indexed, nested, or mapped bean property by name.

3.13.2. Solution

Use PropertyUtils.setProperty() to set any bean property: simple, nested, indexed, or mapped. Pass the bean object to be modified, the name of the property, and the value to setProperty( ); this method will call the appropriate setter method on the supplied object. The following example demonstrates the use of this method to set two properties on a Book bean:

import org.apache.commons.beanutils.PropertyUtils;
Person person1 = new Person( );
person1.setName( "Blah" );
Book book1 = new Book( );
book1.setName( "Blah" );
book1.setAuthor( "Blah" );
PropertyUtils.setProperty( book1, "name", "Some Apache Book" );
PropertyUtils.setProperty( book1, "author", new Person( ) );
PropertyUtils.setProperty( book1, "author.name", "Ken Coar" );

This code created an instance of the Book bean and the Person bean, and PropertyUtils.setProperty( ) set both a simple and a nested bean property.

3.13.3. Discussion

In addition to simple and nested bean properties, this utility can populate indexed and mapped properties. The following example demonstrates the setting of mapped and indexed bean properties on a Book object:

Book book1 = new Book( );
book1.getChapters( ).add( new Chapter( ) );
book1.getChapters( ).add( new Chapter( ) );
PropertyUtils.setProperty( book1, "name", "Apache: The Definitive Guide" );
PropertyUtils.setProperty( book1, "author", new Person( ) );
PropertyUtils.setProperty( book1, "author.name", "Laurie" );
PropertyUtils.setProperty( book1, "chapters[0].name", "Introduction" );
Apartment apartment = new Apartment( );
apartment.getRooms( ).put( "livingRoom", new Room( ) );
PropertyUtils.setProperty( apartment, "rooms(livingRoom).length", 
                 new Integer(12) );

Assume that the Book bean is associated with a series of Chapter objects each of which have a name property. The Book bean has a chapters property, which is a list. The name of the first chapter is set by referencing the chapters[0].name property.


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.