3.6. Accessing Indexed Bean Properties

Problem

You need to access the nth element of a bean property, which is an array or a List.

Solution

Use PropertyUtils.getIndexed() to retrieve an element at a specific index of an array or a List property. Assuming that the chapters property of the Book object is an instance of List, the following demonstrates the use of getIndexedProperty( ) to access the first element of the list of chapters.

import org.apache.commons.beanutils.PropertyUtils;

// Create a new Book
Book book = new Book( );

// Create a list of Chapters
Chapter chapter1 = new Chapter( );
Chapter chapter2 = new Chapter( );
book.getChapters( ).add( chapter1 );
book.getChapters( ).add( chapter2 );

// Retrieve the first Chapter via a property name and an index.
Chapter chapter = 
                   (Chapter) PropertyUtils.getIndexedProperty(book, "chapters[0]");

Discussion

There are two ways of accessing an indexed property via PropertyUtils: the index can be specified in the name, or it can be specified as a third parameter. The following code uses both versions of getIndexedProperty( ) to retrieve the first chapter from the list of chapters:

import org.apache.commons.beanutils.PropertyUtils;

Book book = new Book( );

Chapter chapter1 = new Chapter( );
Chapter chapter2 = new Chapter( );
List chapters = new ArrayList( );
chapters.add( chapter1 );
chapters.add( chapter2 );

book.setChapters( chapters );

// You can retrieve the first chapters like this...
Chapter chapterOne = 
                   (Chapter) PropertyUtils.getIndexedProperty( book, "chapters[0]" );

// Or... you can retrieve the first chapter like this...
chapterOne =
                   (Chapter) PropertyUtils.getIndexedProperty( book, "chapters", 0 );

In the previous example, the first version of getIndexedProperty( ) accepts a string specifying an indexed bean property—chapters[0]. If this string is not well-formed, PropertyUtils will throw an IllegalArgumentException; chapters[zero] and chapters['zero'] will cause an exception because neither index is an integer value, and chapters]0[ will cause an exception because the brackets are transposed. The second call to getIndexedProperty( ) is preferred because there is less risk that a parsing error will throw an IllegalArgumentException.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.198.94