O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.4. Accessing Simple Bean Properties

Problem

You need to access a simple bean property by name.

Solution

Use PropertyUtils.getSimpleProperty() to access a bean property by name; this method takes the name of a property and returns the value of that property. The following example uses this method to retrieve the name property from a Person bean:

import org.apache.commons.beanutils.PropertyUtils;

Person person = new Person( );
person.setName( "Alex" );    

String name = (String) PropertyUtils.getSimpleProperty( person, "name" );
System.out.println( name );

PropertyUtils.getSimpleProperty( ) invokes the public method getName( ) on an instance of Person, returning the value of the name property. The previous example executes and prints out the name “Alex.”

Discussion

A simple bean property is a private member variable that can be accessed with a getter method. If a property can be read via a getter method, that getter method is said to be the read method for the named property. If the property can be modified with a setter method, that setter method is said to be the write method for the named property. The Person bean in Example 3-4 defines two simple bean properties, name and favoriteColor.

Example 3-4. A Person bean with two simple properties

package com.discursive.jccook.bean; public class Person { private String name; private String favoriteColor; public Person( ) {} public String getName( ) { return name; } public void setName(String name) { this.name = name; } public String getFavoriteColor( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required