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 RichmondLong 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access