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)" );
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.
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 to specify the map property in the second
argument and the key in the third argument. The code here uses two
different versions of getMappedProperty(
) to retrieve the same value from the rooms map
property:
import java.util.Map;
import java.util.HashMap;
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 livingRoom key
Room room =
(Room) PropertyUtils.getMappedProperty( apartment,
"rooms(Dining Room)" );
// Or.. retrieve the livingRoom key with 3 parameters -
// equivalent to previous
room =
(Room) PropertyUtils.getMappedProperty( apartment, "rooms",
"Dining Room" );
What was true for getIndexedProperty(
) is also true for getMappedProperty(
). In the previous example, the first call to getMappedProperty( ) specifies a key with a
string—rooms(Dining Room). If
getMappedProperty( ) is unable to
parse this string, an IllegalArgumentException will be thrown;
rooms[DiningRoom) and rooms((DiningRoom) will both throw IllegalArgumentException because the property
string is not well-formed. The second call to getMappedProperty( ) reduces the risk of a
property string parsing error because the key is specified in a third
parameter.
