3.14. Testing Property Access

Problem

You need to test a bean property to see if it can be read from or written to.

Solution

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

Discussion

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( ...

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.