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 ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.