3.5. Accessing Nested Bean Properties

Problem

You need to access a nested bean property.

Solution

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

Discussion

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.

Structure of two simple beans: Book and Person

Figure 3-3. Structure of two simple beans: Book and Person

The following example demonstrates a combination of getSimpleProperty( ) and getNestedProperty( ), retrieving a book name ...

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.