3.7. Accessing Mapped Bean Properties
Problem
You need to retrieve values
from a bean property of type
Map.
Solution
Use PropertyUtils.getMappedProperty()
to obtain values from a map property. The
code here retrieves the value corresponding to the key
“Dining Room” from the
room
map property of the
Apartment bean:
import org.apache.commons.beanutils.PropertyUtils; Room dining = new Room( ); dining.setArea( 20 ); dining.setCarpeted( true ); dining.setFurnished( true ); Map rooms = new HashMap( ); rooms.put( "Dining Room", dining ); Apartment apartment = new Apartment( ); apartment.setRooms( rooms );// Retrieve the Dining Room objectRoom room =PropertyUtils.getMappedProperty( apartment, "rooms(Dining Room)" );
Discussion
The code shown in the Solution section retrieves the value from the
rooms
map corresponding to the
key “Dining
Room”—rooms(Dining
Room). The call to getMappedProperty( ) is the equivalent of calling apartment.getRooms( ).get("Dining
Room"). Figure 3-4 illustrates the structure and relationship of
these two beans used, Apartment and
Room.

Figure 3-4. Diagram of the Apartment and Room beans
getMappedProperty( ) works only if the specified
Map has String keys.
getMappedProperty( ) takes the string between
( and ) and retrieves the value
corresponding to this string.
There is another version of PropertyUtils.getMappedProperty() that takes a third argument, allowing you ...
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