3.19. Getting and Setting Properties as Strings

Problem

You need to persist a bean to a text file, or populate a bean’s properties from a String.

Solution

Use BeanUtils to get and set bean properties with strings. This utility contains many of the same functions as PropertyUtils with one major exception; instead of returning the Object value of the property, BeanUtils returns and expects a string representation of a value. The following code uses BeanUtils to populate a bean that is dependent on user input:

import java.util.*;
import org.apache.commons.beanutils.*;

Person person = new Person( );
person.setAge( new Integer( 45 ) );
person.setName( "Donald" );
person.setOccupation( "Salesman" );

// Get the Age as a String
               String ageString = BeanUtils.getProperty( person, "age" );

               // Set the Age from a String
               BeanUtils.setProperty( person, "age", "50" );

Discussion

BeanUtils come in handy when a bean is populated from a user-supplied input like standard input or the parameters of an HTTP request. In fact, BeanUtils started as the mechanism used to populate a Struts ActionForm from the contents of an HTTP request. When the Struts ActionServlet receives a request that is mapped to an Action, the ActionServlet calls a method in RequestUtils, which examines the request and sets any properties on the relevant ActionForm. Because the inner workings of Struts are outside the scope of this book, Example 3-7 takes a String input from System.in and sets the age property of Person.

Example 3-7. Using ...

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.