`
hanhan8020
  • 浏览: 45690 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

Creating a Map of Bean Properties

 
阅读更多

  Creating a Map of Bean Properties

 

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.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics