Use PropertyUtils.isReadable()
and PropertyUtils.isWritable(
)
to see if a bean property is readable or writable. The
following code tests the name
property of the Book
bean to see if
it is readable and writable:
import org.apache.commons.beanutils.PropertyUtils; // Create a Book demonstrating the getter and setter for "name" Book book1 = new Book( ); book1.setName( "Blah" ); String name = book1.getName( ); // Can we read and write "name" boolean nameReadable = PropertyUtils.isReadable( book, "name" ); boolean nameWritable = PropertyUtils.isWritable( book, "name" ); System.out.println( "Is name readable? " + nameReadable ); System.out.println( "Is name writable? " + nameWritable );
The name
property is both
readable and writable, so the nameReadable
and nameWritable
variables will both be true. The
output of this example is as follows:
Is name readable? true Is name writable? true
In addition to working with simple properties, isReadable()
and isWritable( )
also work on nested, indexed,
and mapped properties. The following example demonstrates the use of
these methods to check access to the indexed, quadruple-nested, mapped
bean property length
:
Book book1 = new Book( ); book1.getChapters( ).add( new Chapter( ) ); boolean isReadable = PropertyUtils.isReadable( book, "chapters[0].author.apartment.rooms(livingRoom).length"); boolean isWritable = PropertyUtils.isWritable( book, "chapters[0].author.apartment.rooms(livingRoom).length");
PropertyUtils.isReadable( )
returns true if a specified bean property can be obtained via a public
getter method, and PropertyUtils.isWritable(
)
returns true if a specified bean property corresponds to a
public setter method. This is an overly complex example, but it
demonstrates the versatility of PropertyUtils.isReadable( )
and of PropertyUtils.isWritable( )
.