3.9. Determining the Type of a Bean Property

Problem

You need to determine the type of a bean property.

Solution

Use PropertyUtils.getPropertyType( ) to determine the type of a bean property. This utility will return a Class object that represents the return type of the property’s getter method. The following example uses this method to obtain the return type for the author property on the Book bean:

import org.apache.commons.beanutils.PropertyUtils

Book book = new Book( );

Class type = PropertyUtils.getPropertyType( book, "author" );

System.out.println( "book.author type: " + type.getName( ) );

This example retrieves and displays the type of the author property on Book, which happens to be a Person object. The type of the property is returned and printed to the console:

book.author type: org.test.Person

Discussion

PropertyUtils.getPropertyType() also works for a complex bean property. Passing a nested, indexed, or mapped bean property to this utility will return the type of the last property specified. The following code retrieves the type of a nested, indexed property—chapters[0].name:

import org.apache.commons.beanutils.PropertyUtils;

Chapter chapter = new Chapter( );
chapter.setName( "Chapter 3 BeanUtils" );
chapter.setLength( new Integer(40) );

List chapters = new ArrayList( );
chapters.add( chapter );

Book book = new Book( );
book.setName( "Jakarta Commons Cookbook" );
book.setAuthor( "Dude" );
book.setChapters( chapters );

String property = "chapters[0].name";
               Class propertyType = PropertyUtils.getPropertyType(book, property);

System.out.println( property + " type: " + propertyType.getName( ) );

This code retrieves the type of the name property from an instance of the Chapter retrieved as an indexed property, and it prints the following output:

chapters[0].name type: java.lang.String

PropertyUtils contains another method to retrieve a PropertyDescriptor-- PropertyUtils.getPropertyDescriptor( ). This method takes a reference to any bean property, simple or complex, and returns an object describing the type of a property and providing access to the read and write methods of a property. The following code excerpt obtains the PropertyDescriptor of a nested, indexed property—chapters[0].name:

String property = "chapters[0].name";

PropertyDescriptor descriptor = 
    PropertyUtils.getPropertyDescriptor(book, property);

Class propertyType = descriptor.getPropertyType( ); 
Method writeMethod = descriptor.getWriteMethod( );
Method readMethod = descriptor.getReadMethod( );
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.227.4