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