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 object
Room 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 ...
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.