3.17. Wrapping a Bean with a Map

Problem

You need to expose a bean’s properties as a Map, and operate on the bean properties as if they were entries in a Map.

Solution

Wrap any bean in a BeanMap . This Map implementation uses introspection to provide access to bean properties as if they were key/value pairs in a map. This code wraps a Person bean with BeanMap, iterating through every key and accessing bean properties with get( ):

import java.util.*;
import org.apache.commons.collections.BeanMap;

Person person = new Person( );
person.setName( "Jim" );
person.setAge( new Integer( 28 ) );
person.setOccupation( "Developer" );

Map beanMap = new BeanMap( person );

Set keys = beanMap.keySet( );
Iterator keyIterator = keys.iterator( );
while( keyIterator.hasNext( ) ) {
   String propertyName = (String) keyIterator.next( );

   System.out.println( "Property: " + propertyName +
                       ", Value: " + beanMap.get( propertyName ) +
                       ", Type: " + beanMap.getType( propertyName ).
                       toString( ) );
}

The Person bean has the following properties: age, name, and occupation; an instance of this bean is created and passed to the constructor of BeanMap. The following output is created by iterating over the key set of beanMap:

Property: Age, Value: 28, Type: java.lang.String
Property: Name, Value: Jim, Type: java.lang.Integer
Property: Occupation, Value: Developer, Type: java.lang.String

Discussion

The previous example demonstrates the use of PropertyUtils.describe( ) to create a Map containing bean properties. BeanMap not ...

Get Jakarta Commons Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.