Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

3.16. Creating a Map of Bean Properties

3.16.1. Problem

You need to create a Map that contains every property in a bean.

3.16.2. Solution

Use PropertyUtils.describe() to generate a Map containing all of the readable bean properties from a bean instance. Supply an instance of a bean and this method will return a Map containing all readable bean properties. The code shown here demonstrates the use of PropertyUtils.describe( ) to describe a Person bean:

import java.util.*;
import org.apache.commons.beanutils.PropertyUtils;
// Create a Person and a Book bean instance
Person person = new Person( );
person.setName( "Some Dude" );
Book book = new Book( );
book.setName( "Some Silly Computer Book" );
book.setAuthor( person );
// Describe both beans with a Map
Map bookMap = PropertyUtils.describe( book );
Map authorMap = PropertyUtils.describe( bookMap.get("book") );
System.out.println( "Book Name: " + bookMap.get( "name" ) );
System.out.println( "Author Name: " + authorMap.get( "name" ) );

3.16.3. Discussion

The previous example involves a Book bean with a name and author property; the author property is a Person bean with one property: name. The two maps, bookMap and authorMap, contain keys for every defined bean property, and two of those properties are printed out:

Book Name: Some Silly Computer Book
Author Name: Some Dude

The map returned from PropertyUtils.describe( ) is a HashMap that contains every property from the bean to be described. Internally, PropertyUtils.describe() uses PropertyUtils.getPropertyDescriptors( ) to obtain the list of properties to put into this map.

3.16.4. See Also

Recipe 3.17 demonstrates the use of the BeanMap to wrap a bean and expose a bean's properties via the Map interface.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.