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" );
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 BeanUtils to populate a bean from user input
import java.io.*; public class ReadAge { public static void main (String[] args) throw Exception { // Prompt for an Age System.out.print("Enter Age: "); // open up standard input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String ageString = null; ageString = br.readLine( );// Set the Integer property with a String
Person person = new Person( );
BeanUtils.setProperty( person, "age", ageString );
} }
When BeanUtils
sets the age
property, it uses a set of registered Converter
instances that are available to translate between a
String
and an Object
. Behind
the scenes, BeanUtils
used the
IntegerConverter
class to convert the
user-supplied String
to an
Integer
object. For a full list of converters,
read the documentation for the
org.apache.commons.beanutils.converters
package.
The BeanUtils Javadoc is available at http://jakarta.apache.org/commons/beanutils/api/index.html.
18.189.178.237