O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required