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( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access