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
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( "Common Java 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( );