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 City object richmond; it is equivalent to the following code excerpt:

Region region = (Region) country.getRegions( ).get(0);
City city = (City) region.getCities( ).get("Richmond");
Long population = city.getPopulation( );

Figure 3-5 displays the structure of these three beans: Country, Region, and City.

The Country, Region, and City beans

Figure 3-5. The Country, Region, and City beans

When accessing a bean property, you can use PropertyUtils.getProperty( ) in lieu of the methods introduced in the previous four recipes. The getProperty( ) method parses the supplied property name, splitting the name as the period character. Once this property has been split, this utility parses each token and passes the string to the appropriate method—getSimpleProperty(), getNestedProperty( ), getIndexedProperty( ), or getMappedProperty( ).

See Also

Bean properties may also be retrieved using a simple expression language, such as Expression Language (EL) or Java Expression Language (JEXL). For more information about retrieving bean properties using an expression language, see Recipe 12.1.

Bean properties may also be retrieved using an XPath expression. For more information, see Recipe 12.1.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.233.43