Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

3.14. Testing Property Access

3.14.1. Problem

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

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

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


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.