3.13. Setting a Bean Property

Problem

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

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.

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

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.