3.16. Creating a Map of Bean Properties
Problem
You need to create a
Map
that contains every property in a
bean.
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" ) );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( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access