Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Package org.apache.commons.beanutils

The Bean Introspection Utilities component of the Jakarta Commons subproject offers low-level utility classes that assist in getting and setting property values on Java classes that follow the naming design patterns outlined in the JavaBeans Specification, as well as mechanisms for dynamically defining and accessing bean properties.


Interface Summary
Converter General purpose data type converter that can be registered and used within the BeanUtils package to manage the conversion of objects from one type to another.
DynaBean A DynaBean is a Java object that supports properties whose names and data types, as well as values, may be dynamically modified.
DynaClass A DynaClass is a simulation of the functionality of java.lang.Class for classes implementing the DynaBean interface.
MutableDynaClass A specialized extension to DynaClass that allows properties to be added or removed dynamically.

Class Summary
A Class used in MethodUtils test
BasicDynaBean Minimal implementation of the DynaBean interface.
BasicDynaBeanTestCase Test Case for the BasicDynaBean implementation class.
BasicDynaClass Minimal implementation of the DynaClass interface.
BeanCollectionsTestSuite Test suite which runs all the test cases application to beans in collections.
BeanComparator This comparator compares two beans by the specified bean property.
BeanComparatorTestCase Test Case for the BeanComparator class.
BeanificationTestCase Test Case for changes made during Beanutils Beanification
BeanMap An implementation of Map for JavaBeans which uses introspection to get and put properties in the bean.
BeanMap.Entry Map entry used by BeanMap.
BeanPredicate Predicate implementation that applies the given Predicate to the result of calling the given property getter.
BeanPropertyValueChangeClosure Closure that sets a property.
BeanPropertyValueChangeClosureTest Test cases for BeanPropertyValueChangeClosure.
BeanPropertyValueEqualsPredicate Predicate that evaluates a property value against a specified value.
BeanPropertyValueEqualsPredicateTest Test cases for BeanPropertyValueEqualsPredicateTest.
BeanToPropertyValueTransformer Transformer that outputs a property value.
BeanToPropertyValueTransformerTest Test cases for BeanToPropertyValueTransformer.
BeanUtils Utility methods for populating JavaBeans properties via reflection.
BeanUtilsBean JavaBean property population methods.
BeanUtilsBenchCase JUnit Test Case containing microbenchmarks for BeanUtils.
BeanUtilsTestCase Test Case for the BeanUtils class.
BeanWithInnerBean Bean with inner bean.
BenchBean Plain old java bean (POJO) for microbenchmarks.
ConstructorUtils Utility reflection methods focussed on constructors, modelled after MethodUtils.
ConstructorUtilsTestCase Test case for ConstructorUtils
ContextClassLoaderLocal A value that is provided per (thread) context classloader.
ConvertingWrapDynaBean Implementation of DynaBean that wraps a standard JavaBean instance, so that DynaBean APIs can be used to access its properties, though this implementation allows type conversion to occur when properties are set.
ConvertUtils Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.
ConvertUtilsBean Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.
ConvertUtilsTestCase Test Case for the ConvertUtils class.
DynaBeanUtilsTestCase Test case for BeanUtils when the underlying bean is actually a DynaBean.
DynaProperty The metadata describing an individual property of a DynaBean.
DynaPropertyUtilsTestCase Test accessing DynaBeans transparently via PropertyUtils.
DynaResultSetTestCase Test accessing ResultSets via DynaBeans.
DynaRowSetTestCase Test accessing RowSets via DynaBeans.
ExtendMapBean Used to test
JDBCDynaClass Provides common logic for JDBC implementations of DynaClass.
LazyDynaBean DynaBean which automatically adds properties to the DynaClass and provides Lazy List and Lazy Map features.
LazyDynaBeanTestCase Test Case for the LazyDynaBean implementation class.
LazyDynaClass DynaClass which implements the MutableDynaClass interface.
LazyDynaClassTestCase Test Case for the LazyDynaClass implementation class.
LazyDynaMap Provides a light weight DynaBean facade to a Map with lazy map/list processing.
LazyDynaMapTestCase Test Case for the LazyDynaMap implementation class.
MappedPropertyDescriptor A MappedPropertyDescriptor describes one mapped property.
MappedPropertyTestBean Just a java bean (JAJB) to try to replicate a reported bug
MethodUtils Utility reflection methods focussed on methods in general rather than properties in particular.
MethodUtils.MethodDescriptor Represents the key to looking up a Method by reflection.
MethodUtilsTestCase Test case for MethodUtils
NestedTestBean Specialist test bean for complex nested properties.
PrimitiveBean Bean that has primitive properties
PropertyUtils Utility methods for using Java Reflection APIs to facilitate generic property getter and setter operations on Java objects.
PropertyUtilsBean Utility methods for using Java Reflection APIs to facilitate generic property getter and setter operations on Java objects.
PropertyUtilsBenchCase JUnit Test Case containing microbenchmarks for PropertyUtils.
PropertyUtilsTestCase Test Case for the PropertyUtils class.
ResultSetDynaClass Implementation of DynaClass for DynaBeans that wrap the java.sql.Row objects of a java.sql.ResultSet.
ResultSetIterator Implementation of java.util.Iterator returned by the iterator() method of ResultSetDynaClass.
RowSetDynaClass Implementation of DynaClass that creates an in-memory collection of DynaBeans representing the results of an SQL query.
TestBean General purpose test bean for JUnit tests for the "beanutils" component.
TestBeanMap Test cases for BeanMap
TestBeanPackageSubclass This is a package private subclass of TestBean.
TestBeanPublicSubclass This is a public subclass of TestBean.
TestResultSet Mock object that implements enough of java.sql.ResultSet to exercise the ResultSetDyaClass functionality.
TestResultSetMetaData Mock object that implements enough of java.sql.ResultSetMetaData to exercise the ResultSetDyaClass functionality.
ThrowExceptionConverter Converter implementation that throws a PassTestException when convert is called.
WrapDynaBean Implementation of DynaBean that wraps a standard JavaBean instance, so that DynaBean APIs can be used to access its properties.
WrapDynaBeanTestCase Test Case for the WrapDynaBean implementation class.
WrapDynaClass Implementation of DynaClass for DynaBeans that wrap standard JavaBean instances.

Exception Summary
BeanAccessLanguageException Thrown to indicate that the Bean Access Language cannot execute query against given bean.
ConversionException A ConversionException indicates that a call to Converter.convert() has failed to complete successfully.
NestedNullException Thrown to indicate that the Bean Access Language cannot execute query against given bean since a nested bean referenced is null.
PassTestException Just a runtime exception.

Package org.apache.commons.beanutils Description

The Bean Introspection Utilities component of the Jakarta Commons subproject offers low-level utility classes that assist in getting and setting property values on Java classes that follow the naming design patterns outlined in the JavaBeans Specification, as well as mechanisms for dynamically defining and accessing bean properties.

Table of Contents

  1. Overview
  2. Standard JavaBeans
  3. Dynamic Beans (DynaBeans)
  4. Data Type Conversions
  5. Frequently Asked Questions



The JavaBeans name comes from a Java API specification for a component architecture for the Java language. Writing Java classes that conform to the JavaBeans design patterns makes it easier for Java developers to understand the functionality provided by your class, as well as allowing JavaBeans-aware tools to use Java's introspection capabilities to learn about the properties and operations provided by your class, and present them in a visually appealing manner in development tools.

The JavaBeans Specification describes the complete set of characteristics that makes an arbitrary Java class a JavaBean or not -- and you should consider reading this document to be an important part of developing your Java programming skills. However, the required characteristics of JavaBeans that are important for most development scenarios are listed here:

Using standard Java coding techniques, it is very easy to deal with JavaBeans if you know ahead of time which bean classes you will be using, and which properties you are interested in:

        Employee employee = ...;
        System.out.println("Hello " + employee.getFirstName() + "!");

External Dependencies

The commons-beanutils package requires that the following additional packages be available in the application's class path at runtime:

Standard JavaBeans


As described above, the standard facilities of the Java programming language make it easy and natural to access the property values of your beans using calls to the appropriate getter methods. But what happens in more sophisticated environments where you do not necessarily know ahead of time which bean class you are going to be using, or which property you want to retrieve or modify? The Java language provides classes like java.beans.Introspector, which can examine a Java class at runtime and identify for you the names of the property getter and setter methods, plus the Reflection capabilities to dynamically call such a method. However, these APIs can be difficult to use, and expose the application developer to many unnecessary details of the underlying structure of Java classes. The APIs in the BeanUtils package are intended to simplify getting and setting bean properties dynamically, where the objects you are accessing -- and the names of the properties you care about -- are determined at runtime in your application, rather than as you are writing and compiling your application's classes.

This is the set of needs that are satisfied by the static methods of the PropertyUtils class, which are described further in this section. First, however, some further definitions will prove to be useful:

The general set of possible property types supported by a JavaBean can be broken into three categories -- some of which are supported by the standard JavaBeans specification, and some of which are uniquely supported by the BeanUtils package:

A variety of API methods are provided in the PropertyUtils class to get and set property values of all of these types. In the code fragments below, assume that there are two bean classes defined with the following method signatures:

    public class Employee {
        public Address getAddress(String type);
        public void setAddress(String type, Address address);
        public Employee getSubordinate(int index);
        public void setSubordinate(int index, Employee subordinate);
        public String getFirstName();
        public void setFirstName(String firstName);
        public String getLastName();
        public void setLastName(String lastName);

Basic Property Access

Getting and setting simple property values is, well, simple :-). Check out the following API signatures in the Javadocs:

Using these methods, you might dynamically manipulate the employee's name in an application:

    Employee employee = ...;
    String firstName = (String)
      PropertyUtils.getSimpleProperty(employee, "firstName");
    String lastName = (String)
      PropertyUtils.getSimpleProperty(employee, "lastName");
    ... manipulate the values ...
    PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
    PropertyUtils.setSimpleProperty(employee, "lastName", lastName);

For indexed properties, you have two choices - you can either build a subscript into the "property name" string, using square brackets, or you can specify the subscript in a separate argument to the method call:

Only integer constants are allowed when you add a subscript to the property name. If you need to calculate the index of the entry you wish to retrieve, you can use String concatenation to assemble the property name expression. For example, you might do either of the following:

    Employee employee = ...;
    int index = ...;
    String name = "subordinate[" + index + "]";
    Employee subordinate = (Employee)
      PropertyUtils.getIndexedProperty(employee, name);

    Employee employee = ...;
    int index = ...;
    Employee subordinate = (Employee)
      PropertyUtils.getIndexedProperty(employee, "subordinate", index);

In a similar manner, there are two possible method signatures for getting and setting mapped properties. The difference is that the extra argument is surrounded by parentheses ("(" and ")") instead of square brackets, and it is considered to be a String-value key used to get or set the appropriate value from an underlying map.

You can, for example, set the employee's home address in either of these two manners:

    Employee employee = ...;
    Address address = ...;
    PropertyUtils.setMappedProperty(employee, "address(home)", address);

    Employee employee = ...;
    Address address = ...;
    PropertyUtils.setMappedProperty(employee, "address", "home", address);

Nested Property Access

In all of the examples above, we have assumed that you wished to retrieve the value of a property of the bean being passed as the first argument to a PropertyUtils method. However, what if the property value you retrieve is really a Java object, and you wish to retrieve a property of that object instead?

For example, assume we really wanted the city property of the employee's home address. Using standard Java programming techniques for direct access to the bean properties, we might write:

    String city = employee.getAddress("home").getCity();

The equivalent mechanism using the PropertyUtils class is called nested property access. To use this approach, you concatenate together the property names of the access path, using "." separators -- very similar to the way you can perform nested property access in JavaScript.

The PropertyUtils equivalent to the above Java expression would be:

    String city = (String)
      PropertyUtils.getNestedProperty(employee, "address(home).city");

Finally, for convenience, PropertyUtils provides method signatures that accept any arbitrary combination of simple, indexed, and mapped property access, using any arbitrary level of nesting:

which you might use like this:

    Employee employee = ...;
    String city = (String) PropertyUtils.getProperty(employee,

Dynamic Beans (DynaBeans)


The PropertyUtils class described in the preceding section is designed to provide dynamic property access on existing JavaBean classes, without modifying them in any way. A different use case for dynamic property access is when you wish to represent a dynamically calculated set of property values as a JavaBean, but without having to actually write a Java class to represent these properties. Besides the effort savings in not having to create and maintain a separate Java class, this ability also means you can deal with situations where the set of properties you care about is determined dynamically (think of representing the result set of an SQL select as a set of JavaBeans ...).

To support this use case, the BeanUtils package provides the DynaBean interface, which must be implemented by a bean class actually implementing the interface's methods, and the associated DynaClass interface that defines the set of properties supported by a particular group of DynaBeans, in much the same way that java.lang.Class defines the set of properties supported by all instances of a particular JavaBean class.

For example, the Employee class used in the examples above might be implemented as a DynaBean, rather than as a standard JavaBean. You can access its properties like this:

    DynaBean employee = ...; // Details depend on which
                             // DynaBean implementation you use
    String firstName = (String) employee.get("firstName");
    Address homeAddress = (Address) employee.get("address", "home");
    Object subordinate = employee.get("subordinate", 2);

One very important convenience feature should be noted: the PropertyUtils property getter and setter methods understand how to access properties in DynaBeans. Therefore, if the bean you pass as the first argument to, say, PropertyUtils.getSimpleProperty() is really a DynaBean implementation, the call will get converted to the appropriate DynaBean getter method transparently. Thus, you can base your application's dynamic property access totally on the PropertyUtils APIs, if you wish, and use them to access either standard JavaBeans or DynaBeans without having to care ahead of time how a particular bean is implemented.

Because DynaBean and DynaClass are interfaces, they may be implemented multiple times, in different ways, to address different usage scenarios. The following subsections describe the implementations that are provided as a part of the standard BeanUtils package, although you are encouraged to provide your own custom implementations for cases where the standard implementations are not sufficient.

BasicDynaBean and BasicDynaClass

The BasicDynaBean and BasicDynaClass implementation provides a basic set of dynamic property capabilities where you want to dynamically define the set of properties (described by instances of DynaProperty). You start by defining the DynaClass that establishes the set of properties you care about:

    DynaProperty[] props = new DynaProperty[]{
        new DynaProperty("address", java.util.Map.class),
        new DynaProperty("subordinate", mypackage.Employee[].class),
        new DynaProperty("firstName", String.class),
        new DynaProperty("lastName",  String.class)
    BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props);

Note that the 'dynaBeanClass' argument (in the constructor of BasicDynaClass) can have the value of null. In this case, the value of dynaClass.getDynaBeanClass will just be the Class for BasicDynaBean.

Next, you use the newInstance() method of this DynaClass to create new DynaBean instances that conform to this DynaClass, and populate its initial property values (much as you would instantiate a new standard JavaBean and then call its property setters):

    DynaBean employee = dynaClass.newInstance();
    employee.set("address", new HashMap());
    employee.set("subordinate", new mypackage.Employee[0]);
    employee.set("firstName", "Fred");
    employee.set("lastName", "Flintstone");

Note that the DynaBean class was declared to be DynaBean instead of BasicDynaBean. In general, if you are using DynaBeans, you will not want to care about the actual implementation class that is being used -- you only care about declaring that it is a DynaBean so that you can use the DynaBean APIs.

As stated above, you can pass a DynaBean instance as the first argument to a PropertyUtils method that gets and sets properties, and it will be interpreted as you expect -- the dynamic properties of the DynaBean will be retrieved or modified, instead of underlying properties on the actual BasicDynaBean implementation class.

ResultSetDynaClass (Wraps ResultSet in DynaBeans)

A very common use case for DynaBean APIs is to wrap other collections of "stuff" that do not normally present themselves as JavaBeans. One of the most common collections that would be nice to wrap is the java.sql.ResultSet that is returned when you ask a JDBC driver to perform a SQL SELECT statement. Commons BeanUtils offers a standard mechanism for making each row of the result set visible as a DynaBean, which you can utilize as shown in this example:

  Connection conn = ...;
  Statement stmt = conn.createStatement();
  ResultSet rs = stmt.executeQuery
    ("select account_id, name from customers");
  Iterator rows = (new ResultSetDynaClass(rs)).iterator();
  while (rows.hasNext()) {
    DynaBean row = (DynaBean);
    System.out.println("Account number is " +
                       row.get("account_id") +
                       " and name is " + row.get("name"));

RowSetDynaClass (Disconnected ResultSet as DynaBeans)

Although ResultSetDynaClass is a very useful technique for representing the results of an SQL query as a series of DynaBeans, an important problem is that the underlying ResultSet must remain open throughout the period of time that the rows are being processed by your application. This hinders the ability to use ResultSetDynaClass as a means of communicating information from the model layer to the view layer in a model-view-controller architecture such as that provided by the Struts Framework, because there is no easy mechanism to assure that the result set is finally closed (and the underlying Connection returned to its connection pool, if you are using one).

The RowSetDynaClass class represents a different approach to this problem. When you construct such an instance, the underlying data is copied into a set of in-memory DynaBeans that represent the result. The advantage of this technique, of course, is that you can immediately close the ResultSet (and the corresponding Statement), normally before you even process the actual data that was returned. The disadvantage, of course, is that you must pay the performance and memory costs of copying the result data, and the result data must fit entirely into available heap memory. For many environments (particularly in web applications), this tradeoff is usually quite beneficial.

As an additional benefit, the RowSetDynaClass class is defined to implement, so that it (and the DynaBeans that correspond to each row of the result) can be conveniently serialized and deserialized (as long as the underlying column values are also Serializable). Thus, RowSetDynaClass represents a very convenient way to transmit the results 0f an SQL query to a remote Java-based client application (such as an applet).

The normal usage pattern for a RowSetDynaClass will look something like this:

    Connection conn = ...;  // Acquire connection from pool
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT ...");
    RowSetDynaClass rsdc = new RowSetDynaClass(rs);
    ...;                    // Return connection to pool
    List rows = rsdc.getRows();
    ...;                   // Process the rows as desired

WrapDynaBean and WrapDynaClass

OK, you've tried the DynaBeans APIs and they are cool -- very simple get() and set() methods provide easy access to all of the dynamically defined simple, indexed, and mapped properties of your DynaBeans. You'd like to use the DynaBean APIs to access all of your beans, but you've got a bunch of existing standard JavaBeans classes to deal with as well. This is where the WrapDynaBean (and its associated WrapDynaClass) come into play. As the name implies, a WrapDynaBean is used to "wrap" the DynaBean APIs around an existing standard JavaBean class. To use it, simply create the wrapper like this:

    MyBean bean = ...;
    DynaBean wrapper = new WrapDynaBean(bean);
    String firstName = wrapper.get("firstName");

Note that, although appropriate WrapDynaClass instances are created internally, you never need to deal with them.

Data Type Conversions


So far, we've only considered the cases where the data types of the dynamically accessed properties are known, and where we can use Java casts to perform type conversions. What happens if you want to automatically perform type conversions when casting is not possible? The BeanUtils package provides a variety of APIs and design patterns for performing this task as well.

BeanUtils and ConvertUtils Conversions

A very common use case (and the situation that caused the initial creation of the BeanUtils package) was the desire to convert the set of request parameters that were included in a javax.servlet.HttpServletRequest received by a web application into a set of corresponding property setter calls on an arbitrary JavaBean. (This is one of the fundamental services provided by the Struts Framework, which uses BeanUtils internally to implement this functionality.)

In an HTTP request, the set of included parameters is made available as a series of String (or String array, if there is more than one value for the same parameter name) instances, which need to be converted to the underlying data type. The BeanUtils class provides property setter methods that accept String values, and automatically convert them to appropriate property types for Java primitives (such as int or boolean), and property getter methods that perform the reverse conversion. Finally, a populate() method is provided that accepts a java.util.Map containing a set of property values (keyed by property name), and calls all of the appropriate setters whenever the underlying bean has a property with the same name as one of the request parameters. So, you can perform the all-in-one property setting operation like this:

    HttpServletRequest request = ...;
    MyBean bean = ...;
    HashMap map = new HashMap();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      map.put(name, request.getParameterValues(name));
    BeanUtils.populate(bean, map);

The BeanUtils class relies on conversion methods defined in the ConvertUtils class to perform the actual conversions, and these methods are availablve for direct use as well. WARNING - It is likely that the hard coded use of ConvertUtils methods will be deprecated in the future, and replaced with a mechanism that allows you to plug in your own implementations of the Converter interface instead. Therefore, new code should not be written with reliance on ConvertUtils.

Defining Your Own Converters

The ConvertUtils class supports the ability to define and register your own String --> Object conversions for any given Java class. Once registered, such converters will be used transparently by all of the BeanUtils methods (including populate()). To create and register your own converter, follow these steps:

  • Write a class that implements the Converter interface. The convert() method should accept the java.lang.Class object of your application class (i.e. the class that you want to convert to, and a String representing the incoming value to be converted.
  • At application startup time, register an instance of your converter class by calling the ConvertUtils.register() method.

Locale Aware Conversions

The standard classes in org.apache.commons.beanutils are not locale aware. This gives them a cleaner interface and makes then easier to use in situations where the locale is not important.

Extended, locale-aware analogues can be found in org.apache.commons.beanutils.locale . These are built along the same lines as the basic classes but support localization.

Frequently Asked Questions

Why Can't BeanUtils Find My Method?

The BeanUtils package relies on introspection rather than reflection. This means that it will find only JavaBean compliant properties.

There are some subtleties of this specification that can catch out the unwary:

  • A property can have only one set and one get method. Overloading is not allowed.
  • The java.beans.Introspector searches widely for a custom BeanInfo class. If your class has the same name as another with a custom BeanUtils (typically a java API class) then the Introspector may use that instead of creating via reflection based on your class. If this happens, the only solution is to create your own BeanInfo.