3.8. Accessing a Simple, Nested, Indexed, and Mapped Bean Property

Problem

You need to access a nested, indexed, and mapped bean property by name.

Solution

Use PropertyUtils.getProperty() to access any bean property. This single utility can be used to access any bean property be it simple, nested, indexed, mapped, or any combination thereof. The following example accesses a simple property, population, of a nested mapped property, cities, on an indexed property, regions:

import java.util.*;
import org.apache.commons.beanutils.PropertyUtils;

// Create a series of nested beans
City richmond = new City( );
richmond.setName( "Richmond" );
richmond.setPopulation( new Long(500000) );

Map cities = new HashMap( );
cities.put( "richmond", richmond );

Region midAtlantic = new Region( );
midAtlantic.setName( "Mid-Atlantic" );
midAtlantic.setCities( cities );

List regions = new ArrayList( );
regions.add( midAtlantic );

Country country = new Country( );
country.setName( "United States" );
country.setRegions( regions );

// Retrieve the population of Richmond
Long population =
                   (Long) PropertyUtils.getProperty( country, 
                                               "regions[0].cities(richmond).population" );

Most of this code sets up a complex nested object hierarchy to be queried by PropertyUtils.getProperty( ). Retrieving the regions[0].cities(richmond).population property is the equivalent of traversing down a tree of objects and retrieving the bottom-most element—population.

Discussion

The emphasized code retrieves the population of the ...

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.