Use PropertyUtils.getNestedProperty()
to retrieve a nested bean property. Use a period as a
delimiter to identify nested bean properties; one.two.three.four
refers to a property
nested three levels deep—the four
property of the three
property of the
two
property of the one
property. The following example accesses a
nested bean property on a Person
bean, author.name
:
import org.apache.commons.beanutils.PropertyUtils; Book book = new Book( ); book.setName( "Emerson's Essays" ); Person author = new Person( ); author.setName( "Ralph Waldo Emerson" ); book.setAuthor( author ); String authorName = (String) PropertyUtils.getNestedProperty(book, "author.name"); System.out.println( "authorName" );This example retrieves the name property of the author property on the Book object, printing "Ralph Waldo Emerson".
The author
property of Book
is a Person
bean with a name
property; calling getNestedProperty( )
with author.name
retrieves the simple property
author
from Book
and the property name
, which is nested in the author
property. Figure 3-3 shows the Book
and Person
beans that were used in the previous
example.
The following example demonstrates a combination of getSimpleProperty( )
and getNestedProperty( )
, retrieving a book name
and an author name:
General Exception is caught. import org.apache.commons.beanutils.PropertyUtils; // Create an author Person author = new Person( ); author.setName( "Chaucer" ); Book book = new Book( ); book.setName( "The Canterbury Tales" ); book.setAuthor( author ); try { String bookName = (String) PropertyUtils.getSimpleProperty( book, "name" ); String authorName = (String) PropertyUtils.getNestedProperty( book, "author.name" ); System.out.println( "The book is " + bookName ); System.out.println( "The author is " + authorName ); } catch (Exception e) { System.out.println( "There was a problem getting a bean property." ); e.printStackTrace( ); }
When using getNestedProperty(
)
, there is no limit to the number of nesting levels for a
property; demonstrating the retrieval of a deeply nested property, the
following example retrieves the name
property from the state
property of
the address
property of a Person
object:
String propertyName = "address.state.name"; String stateName = (String) PropertyUtils.getNestedProperty( person, propertyName );
This example assumes that the Person
class has a getAddress( )
method
that returns an Address
object with a
getState( )
method and returns a State
object with a getName()
method. The emphasized code in the previous example is the
equivalent of the following three lines of code:
Address address = person.getAddress( ); State state = address.getState( ); String stateName = state.getName( );