org.apache.commons.beanutils

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Library » Apache commons beanutils 1.8.0 BETA src » org.apache.commons.beanutils 
org.apache.commons.beanutils
Package Documentation for org.apache.commons.beanutils Package

The Bean Introspection Utilities component of the Apache 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

1.1 Background

The JavaBeans name comes from a Java API 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:

  • The class must be public, and provide a public constructor that accepts no arguments. This allows tools and applications to dynamically create new instances of your bean, without necessarily knowing what Java class name will be used ahead of time, like this:
            String className = ...;
            Class beanClass = Class.forName(className);
            Object beanInstance = beanClass.newInstance();
    
  • As a necessary consequence of having a no-arguments constructor, configuration of your bean's behavior must be accomplished separately from its instantiation. This is typically done by defining a set of properties of your bean, which can be used to modify its behavior or the data that the bean represents. The normal convention for property names is that they start with a lower case letter, and be comprised only of characters that are legal in a Java identifier.
  • Typically, each bean property will have a public getter and setter method that are used to retrieve or define the property's value, respectively. The JavaBeans Specification defines a design pattern for these names, using get or set as the prefix for the property name with it's first character capitalized. Thus, you a JavaBean representing an employee might have (among others) properties named firstName, lastName, and hireDate, with method signatures like this:
            public class Employee {
                public Employee();   // Zero-arguments constructor
                public String getFirstName();
                public void setFirstName(String firstName);
                public String getLastName();
                public void setLastName(String lastName);
                public Date getHireDate();
                public void setHireDate(Date hireDate);
                public boolean isManager();
                public void setManager(boolean manager);
                public String getFullName();
            }
    
  • As you can see from the above example, there is a special variant allowed for boolean properties -- you can name the getter method with a is prefix instead of a get prefix if that makes for a more understandable method name.
  • If you have both a getter and a setter method for a property, the data type returned by the getter must match the data type accepted by the setter. In addition, it is contrary to the JavaBeans specification to have more than one setter with the same name, but different property types.
  • It is not required that you provide a getter and a setter for every property. In the example above, the fullName property is read-only, because there is no setter method. It is also possible, but less common, to provide write-only properties.
  • It is also possible to create a JavaBean where the getter and setter methods do not match the naming pattern described above. The standard JavaBeans support classes in the Java language, as well as all classes in the BeanUtils package, allow you to describe the actual property method names in a BeanInfo class associated with your bean class. See the JavaBeans Specification for full details.
  • The JavaBeans Specification also describes many additional design patterns for event listeners, wiring JavaBeans together into component hierarchies, and other useful features that are beyond the scope of the BeanUtils package.

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() + "!");

1.2 External Dependencies

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

2. Standard JavaBeans

2.1 Background

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:

  • Simple - Simple, or scalar, properties have a single value that may be retrieved or modified. The underlying property type might be a Java language primitive (such as int, a simple object (such as a java.lang.String), or a more complex object whose class is defined either by the Java language, by the application, or by a class library included with the application.
  • Indexed - An indexed property stores an ordered collection of objects (all of the same type) that can be individually accessed by an integer-valued, non-negative index (or subscript). Alternatively, the entire set of values may be set or retrieved using an array. As an extension to the JavaBeans specification, the BeanUtils package considers any property whose underlying data type is java.util.List (or an implementation of List) to be indexed as well.
  • Mapped - As an extension to standard JavaBeans APIs, the BeanUtils package considers any property whose underlying value is a java.util.Map to be "mapped". You can set and retrieve individual values via a String-valued key.

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);
    }

2.2 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);

2.3 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,
      "subordinate[3].address(home).city");

3. Dynamic Beans (DynaBeans)

3.1 Background

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.

3.2 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.

3.3 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) rows.next();
    System.out.println("Account number is " +
                       row.get("account_id") +
                       " and name is " + row.get("name"));
  }
  rs.close();
  stmt.close();

3.4 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 java.io.Serializable, 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 of 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);
    rs.close();
    stmt.close();
    ...;                    // Return connection to pool
    List rows = rsdc.getRows();
    ...;                   // Process the rows as desired

3.5 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.

3.6 Lazy DynaBeans

You bought into the DynaBeans because it saves coding all those POJO JavaBeans but you're here because lazy caught your eye and wondered whats that about? What makes these flavors of DynaBean lazy are the following features:

  • Lazy property addition - lazy beans use a DynaClass which implements the MutableDynaClass interface. This provides the ability to add and remove a DynaClass's properties. Lazy beans use this feature to automatically add a property which doesn't exist to the DynaClass when the set(name, value) method is called.
  • Lazy List/Array growth - If an indexed property is not large enough to accomodate the index being set then the List or Array is automatically grown so that it is.
  • Lazy List/Array instantiation - if an indexed property doesn't exist then calling the DynaBean's indexed property getter/setter methods (i.e. get(name, index) or set(name, index, value)) results in either a new List or Array being instantiated. If the indexed property has not been defined in the DynaClass then it is automatically added and a default List implementation instantiated.
  • Lazy Map instantiation - if a mapped property doesn't exist then calling the DynaBean's mapped property getter/setter methods (i.e. get(name, key) or set(name, key, value)) results in a new Map being instantiated. If the mapped property has not been defined in the DynaClass then it is automatically added and a default Map implementation instantiated.
  • Lazy Bean instantiation - if a property is defined in the DynaClass as a DynaBean or regular bean and doesn't exist in the DynaBean then LazyDynaBean wiill try to instantiate the bean using a default empty constructor.

1. LazyDynaBean is the standard lazy bean implementation. By default it is associated with a LazyDynaClass which implements the MutableDynaClass interface - however it can be used with any MutableDynaClass implementation. The question is how do I use it? - well it can be as simple as creating a new bean and then calling the getters/setters...

    DynaBean dynaBean = new LazyDynaBean();

    dynaBean.set("foo", "bar");                   // simple

    dynaBean.set("customer", "title", "Mr");      // mapped
    dynaBean.set("customer", "surname", "Smith"); // mapped

    dynaBean.set("address", 0, addressLine1);     // indexed
    dynaBean.set("address", 1, addressLine2);     // indexed
    dynaBean.set("address", 2, addressLine3);     // indexed

2. LazyDynaMap is a light wieght DynaBean facade to a Map with all the usual lazy features. Its light weight because it doesn't have an associated DynaClass containing all the properties. In fact it actually implements the DynaClass interface itself (and MutableDynaClass) and derives all the DynaClass information from the actual contents of the Map. A LazyDynaMap can be created around an existing Map or can instantiate its own Map. After any DynaBean processing has finished the Map can be retrieved and the DynaBean facade discarded.

If you need a new Map then to use....

    DynaBean dynaBean = new LazyDynaMap();        // create DynaBean

    dynaBean.set("foo", "bar");                   // simple
    dynaBean.set("customer", "title", "Mr");      // mapped
    dynaBean.set("address", 0, addressLine1);     // indexed

    Map myMap = dynaBean.getMap()                 // retrieve the Map

or to use with an existing Map ....

    Map myMap = ....                             // exisitng Map
    DynaBean dynaBean = new LazyDynaMap(myMap);  // wrap Map in DynaBean
    dynaBean.set("foo", "bar");                  // set properties

3. LazyDynaList is lazy list for DynaBean's, java.util.Map's or POJO beans. See the Javadoc for more details and example usage.

4. LazyDynaClass extends BasicDynaClass and implements the MutableDynaClass interface. It can be used with other DynaBean implementations, but it is the default DynaClass used by LazyDynaBean. When using the LazyDynaBean there may be no need to have anything to do with the DynaClass However sometimes there is a requirement to set up the DynaClass first - perhaps to define the type of array for an indexed property, or if using the DynaBean in restricted mode (see note below) is required. Doing so is straight forward...

Either create a LazyDynaClass first...

    MutableDynaClass dynaClass = new LazyDynaClass();    // create DynaClass

    dynaClass.add("amount", java.lang.Integer.class);    // add property
    dynaClass.add("orders", OrderBean[].class);          // add indexed property
    dynaClass.add("orders", java.util.TreeMapp.class);   // add mapped property

    DynaBean dynaBean = new LazyDynaBean(dynaClass);     // Create DynaBean with associated DynaClass

or create a LazyDynaBean and get the DynaClass...

    DynaBean dynaBean = new LazyDynaBean();              // Create LazyDynaBean
    MutableDynaClass dynaClass = 
             (MutableDynaClass)dynaBean.getDynaClass();  // get DynaClass

    dynaClass.add("amount", java.lang.Integer.class);    // add property
    dynaClass.add("myBeans", myPackage.MyBean[].class);  // add 'array' indexed property
    dynaClass.add("myMap", java.util.TreeMapp.class);    // add mapped property

NOTE: One feature of MutableDynaClass is that it has a Restricted property. When the DynaClass is restricted no properties can be added or removed from the DynaClass. Neither the LazyDynaBean or LazyDynaMap will add properties automatically if the DynaClass is restricted.

4. Data Type Conversions

4.1 Background

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.

4.2 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.

4.3 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.

4.4 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.

5. Utility Objects And Static Utility Classes

Background

So far, the examples have covered the static utility classes (BeanUtils, ConvertUtils and PropertyUtils). These are easy to use but are somewhat inflexible. These all share the same registered converters and the same caches.

This functionality can also be accessed through utility objects (in fact, the static utility class use worker instances of these classes). For each static utility class, there is a corresponding class with the same functionality that can be instantiated:

Static Utility ClassUtility Object
BeanUtilsBeanUtilsBean
ConvertUtilsConvertUtilsBean
PropertyUtilsPropertyUtilsBean

Creating an instances allow gives guarenteed control of the caching and registration to the code that creates it.

6. Collections

6.1 Comparing Beans

org.apache.commons.beanutils.BeanComparator is a Comparator implementation that compares beans based on a shared property value.

6.2 Operating On Collections Of Beans

The Closure interface in commons-collections encapsulates a block of code that executes on an arbitrary input Object. Commons-collections contains code that allows Closures to be applied to the contents of a Collection. For more details, see the commons-collections documentation.

BeanPropertyValueChangeClosure is a Closure that sets a specified property to a particular value. A typical usage is to combine this with commons-collections so that all the beans in a collection can have a particular property set to a particular value.

For example, set the activeEmployee property to TRUE for an entire collection:

    // create the closure
    BeanPropertyValueChangeClosure closure =
        new BeanPropertyValueChangeClosure( "activeEmployee", Boolean.TRUE );
 
    // update the Collection
    CollectionUtils.forAllDo( peopleCollection, closure );
  

6.3 Querying Or Filtering Collections Of Beans

The Predicate interface in commons-collections encapsulates an evaluation of an input Object that returns either true or false. Commons-collections contains code that allows Predicates to be applied to be used to filter collections. For more details, see the commons-collections documentation.

BeanPropertyValueEqualsPredicate is a Predicate that evaluates a set property value against a given value. A typical usage is (in combination with commons-collections) to filter collections on the basis of a property value.

For example, to filter a collection to find all beans where active employee is false use:

    BeanPropertyValueEqualsPredicate predicate =
        new BeanPropertyValueEqualsPredicate( "activeEmployee", Boolean.FALSE );
 
    // filter the Collection
    CollectionUtils.filter( peopleCollection, predicate );

6.4 Transforming Collections Of Beans

The Transformer interface in commons-collections encapsulates the transformation of an input Object into an output object. Commons-collections contains code that allows Transformers to be applied produce a collection of outputs from a collection of inputs. For more details, see the commons-collections documentation.

BeanToPropertyTransformer is a Transformer implementation that transforms a bean into it's property value.

For example, to find all cities that are contained in the address of each person property of each bean in a collection:

    // create the transformer
    BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( "person.address.city" );
 
    // transform the Collection
    Collection peoplesCities = CollectionUtils.collect( peopleCollection, transformer );
    

7. 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 BeanInfo (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.

How Do I Set The BeanComparator Order To Be Ascending/Descending?

BeanComparator relies on an internal Comparator to perform the actual comparisions. By default, org.apache.commons.collections.comparators.ComparableComparator is used which imposes a natural order. If you want to change the order, then a custom Comparator should be created and passed into the appropriate constructor.

For example:

    import org.apache.commons.collections.comparators.ComparableComparator;
    import org.apache.commons.collections.comparators.ReverseComparator;
    import org.apache.commons.beanutils.BeanComparator;
    ...
    BeanComparator reversedNaturalOrderBeanComparator
        = new BeanComparator("propertyName", new ReverseComparator(new ComparableComparator()));
    Collections.sort(myList, reversedNaturalOrderBeanComparator);
    ...
Java Source File NameTypeComment
A.javaClass
AbstractChild.javaClass
AbstractParent.javaClass
AlphaBean.javaClass
BasicDynaBean.javaClass

Minimal implementation of the DynaBean interface.

BasicDynaBeanTestCase.javaClass

Test Case for the BasicDynaBean implementation class. These tests were based on the ones in PropertyUtilsTestCase because the two classes provide similar levels of functionality.


author:
   Craig R.
BasicDynaClass.javaClass

Minimal implementation of the DynaClass interface.

BeanAccessLanguageException.javaClass Thrown to indicate that the Bean Access Language cannot execute query against given bean.
BeanComparator.javaClass

This comparator compares two beans by the specified bean property.

BeanComparatorTestCase.javaClass

Test Case for the BeanComparator class.

BeanificationTestCase.javaClass
BeanMap.javaClass An implementation of Map for JavaBeans which uses introspection to get and put properties in the bean.
BeanMapTestCase.javaClass
BeanPredicate.javaClass

Predicate implementation that applies the given Predicate to the result of calling the given property getter.

BeanPredicateTestCase.javaClass
BeanPropertyValueChangeClosure.javaClass

Closure that sets a property.

An implementation of org.apache.commons.collections.Closure that updates a specified property on the object provided with a specified value. The BeanPropertyValueChangeClosure constructor takes two parameters which determine what property will be updated and with what value.

public BeanPropertyValueChangeClosure( String propertyName, Object propertyValue )
Will create a Closure that will update an object by setting the property specified by propertyName to the value specified by propertyValue.

Note: Property names can be a simple, nested, indexed, or mapped property as defined by org.apache.commons.beanutils.PropertyUtils.

BeanPropertyValueChangeClosureTestCase.javaClass Test cases for BeanPropertyValueChangeClosure.
BeanPropertyValueEqualsPredicate.javaClass

Predicate that evaluates a property value against a specified value.

An implementation of org.apache.commons.collections.Predicate that evaluates a property value on the object provided against a specified value and returns true if equal; false otherwise. The BeanPropertyValueEqualsPredicate constructor takes two parameters which determine what property will be evaluated on the target object and what its expected value should be.

public BeanPropertyValueEqualsPredicate( String propertyName, Object propertyValue )
Will create a Predicate that will evaluate the target object and return true if the property specified by propertyName has a value which is equal to the the value specified by propertyValue.
BeanPropertyValueEqualsPredicateTestCase.javaClass Test cases for BeanPropertyValueEqualsPredicateTest.
BeanToPropertyValueTransformer.javaClass

Transformer that outputs a property value.

An implementation of org.apache.commons.collections.Transformer that transforms the object provided by returning the value of a specified property of the object.

BeanToPropertyValueTransformerTestCase.javaClass Test cases for BeanToPropertyValueTransformer.
BeanUtils.javaClass

Utility methods for populating JavaBeans properties via reflection.

The implementations are provided by BeanUtilsBean . These static utility methods use the default instance. More sophisticated behaviour can be provided by using a BeanUtilsBean instance.


author:
   Craig R.
BeanUtils2TestCase.javaClass Test Case for the BeanUtilsBean2 .
BeanUtilsBean.javaClass

JavaBean property population methods.

This class provides implementations for the utility methods in BeanUtils . Different instances can be used to isolate caches between classloaders and to vary the value converters registered.


author:
   Craig R.
BeanUtilsBean2.javaClass

BeanUtilsBean implementation that creates a ConvertUtilsBean2 and delegates conversion to ConvertUtilsBean.convert(ObjectClass) .

To configure this implementation for the current context ClassLoader invoke BeanUtilsBean.setInstance(new BeanUtilsBean2());

BeanUtils 1.7.0 delegated all conversion to String to the converter registered for the String.class.

BeanUtilsBenchCase.javaClass JUnit Test Case containing microbenchmarks for BeanUtils.
BeanUtilsTestCase.javaClass

Test Case for the BeanUtils class.

BeanWithInnerBean.javaClass Bean with inner bean.
author:
   John E.
BenchBean.javaClass Plain old java bean (POJO) for microbenchmarks.
author:
   Craig R.
BetaBean.javaClass
Child.javaInterface
ConstructorUtils.javaClass

Utility reflection methods focussed on constructors, modelled after MethodUtils .

ConstructorUtilsTestCase.javaClass
ContextClassLoaderLocal.javaClass An instance of this class represents a value that is provided per (thread) context classloader.

Occasionally it is necessary to store data in "global" variables (including uses of the Singleton pattern).

ConversionException.javaClass

A ConversionException indicates that a call to Converter.convert() has failed to complete successfully.

Converter.javaInterface

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.

Converter subclasses bundled with the BeanUtils library are required to be thread-safe, as users of the library may call conversion methods from more than one thread simultaneously.

Custom converter subclasses created by users of the library can be non-thread-safe if the application using them is single-threaded.

ConvertingWrapDynaBean.javaClass

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.javaClass

Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.

For more details, see ConvertUtilsBean which provides the implementations for these methods.


author:
   Craig R.
ConvertUtilsBean.javaClass

Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.

ConvertUtilsBean2.javaClassConvertUtilsBean implementation that delegates convert() methods to the new ConvertUtilsBean.convert(ObjectClass) method.
ConvertUtilsTestCase.javaClass

Test Case for the ConvertUtils class.


author:
   Craig R.
DynaBean.javaInterface

A DynaBean is a Java object that supports properties whose names and data types, as well as values, may be dynamically modified.

DynaBeanMapDecorator.javaClass

Decorates a DynaBean to provide Map behaviour.

The motivation for this implementation is to provide access to DynaBean properties in technologies that are unaware of BeanUtils and DynaBean s - such as the expression languages of JSTL and JSF.

This can be achieved either by wrapping the DynaBean prior to providing it to the technolody to process or by providing a Map accessor method on the DynaBean implementation:


 public Map getMap() {
 return new DynaBeanMapDecorator(this);
 }

This, for example, could be used in JSTL in the following way to access a DynaBean's fooProperty:

  • ${myDynaBean.map.fooProperty}

Usage

To decorate a DynaBean simply instantiate this class with the target DynaBean :

  • Map fooMap = new DynaBeanMapDecorator(fooDynaBean);

The above example creates a read only Map.

DynaBeanMapDecoratorTestCase.javaClass
DynaBeanUtilsTestCase.javaClass Test case for BeanUtils when the underlying bean is actually a DynaBean.
author:
   Craig R.
DynaClass.javaInterface

A DynaClass is a simulation of the functionality of java.lang.Class for classes implementing the DynaBean interface.

DynaProperty.javaClass

The metadata describing an individual property of a DynaBean.

The meta contains an optional content type property ( DynaProperty.getContentType ) for use by mapped and iterated properties.

DynaPropertyTestCase.javaClass Test case for DynaProperty .
DynaPropertyUtilsTestCase.javaClass Test accessing DynaBeans transparently via PropertyUtils.
author:
   Craig R.
DynaResultSetTestCase.javaClass Test accessing ResultSets via DynaBeans.
author:
   Craig R.
DynaRowSetTestCase.javaClass Test accessing RowSets via DynaBeans.
author:
   Craig R.
ExtendMapBean.javaClass
IndexedPropertyTestCase.javaClass
IndexedTestBean.javaClass Indexed Properties Test bean for JUnit tests for the "beanutils" component.
JDBCDynaClass.javaClass

Provides common logic for JDBC implementations of DynaClass .


author:
   Craig R.
LazyDynaBean.javaClass

DynaBean which automatically adds properties to the DynaClass and provides Lazy List and Lazy Map features.

DynaBeans deal with three types of properties - simple, indexed and mapped and have the following get() and set() methods for each of these types:

  • Simple property methods - get(name) and set(name, value)
  • Indexed property methods - get(name, index) and set(name, index, value)
  • Mapped property methods - get(name, key) and set(name, key, value)

Getting Property Values

Calling any of the get() methods, for a property which doesn't exist, returns null in this implementation.

Setting Simple Properties

The LazyDynaBean will automatically add a property to the DynaClass if it doesn't exist when the set(name, value) method is called.

DynaBean myBean = new LazyDynaBean();
myBean.set("myProperty", "myValue");

Setting Indexed Properties

If the property doesn't exist, the LazyDynaBean will automatically add a property with an ArrayList type to the DynaClass when the set(name, index, value) method is called. It will also instantiate a new ArrayList and automatically grow the List so that it is big enough to accomodate the index being set. ArrayList is the default indexed property that LazyDynaBean uses but this can be easily changed by overriding the defaultIndexedProperty(name) method.

DynaBean myBean = new LazyDynaBean();
myBean.set("myIndexedProperty", 0, "myValue1");
myBean.set("myIndexedProperty", 1, "myValue2");

If the indexed property does exist in the DynaClass but is set to null in the LazyDynaBean, then it will instantiate a new List or Array as specified by the property's type in the DynaClass and automatically grow the List or Array so that it is big enough to accomodate the index being set.

DynaBean myBean = new LazyDynaBean();
MutableDynaClass myClass = (MutableDynaClass)myBean.getDynaClass();
myClass.add("myIndexedProperty", int[].class);
myBean.set("myIndexedProperty", 0, new Integer(10));
myBean.set("myIndexedProperty", 1, new Integer(20));

Setting Mapped Properties

If the property doesn't exist, the LazyDynaBean will automatically add a property with a HashMap type to the DynaClass and instantiate a new HashMap in the DynaBean when the set(name, key, value) method is called.

LazyDynaBeanTestCase.javaClass
LazyDynaClass.javaClass

DynaClass which implements the MutableDynaClass interface.

A MutableDynaClass is a specialized extension to DynaClass that allows properties to be added or removed dynamically.

This implementation has one slightly unusual default behaviour - calling the getDynaProperty(name) method for a property which doesn't exist returns a DynaProperty rather than null.

LazyDynaClassTestCase.javaClass
LazyDynaList.javaClass

Lazy DynaBean List.

There are two main purposes for this class:

  • To provide Lazy List behaviour - automatically growing and populating the List with either DynaBean, java.util.Map or POJO Beans.
  • To provide a straight forward way of putting a Collection or Array into the lazy list and a straight forward way to get it out again at the end.

All elements added to the List are stored as DynaBean's:

  • java.util.Map elements are "wrapped" in a LazyDynaMap.
  • POJO Bean elements are "wrapped" in a WrapDynaBean.
  • DynaBean's are stored un-changed.

toArray()

The toArray() method returns an array of the elements of the appropriate type.

LazyDynaListTestCase.javaClass
LazyDynaMap.javaClass

Provides a light weight DynaBean facade to a Map with lazy map/list processing.

Its a light weight DynaBean implementation because there is no actual DynaClass associated with this DynaBean - in fact it implements the DynaClass interface itself providing pseudo DynaClass behaviour from the actual values stored in the Map.

As well providing rhe standard DynaBean access to the Map's properties this class also provides the usual Lazy behaviour:

  • Properties don't need to be pre-defined in a DynaClass
  • Indexed properties (Lists or Arrays) are automatically instantiated and grown so that they are large enough to cater for the index being set.
  • Mapped properties are automatically instantiated.

Restricted DynaClass

This class implements the MutableDynaClass interface. MutableDynaClass have a facility to restrict the DynaClass so that its properties cannot be modified.

LazyDynaMapTestCase.javaClass
MappedPropertyChildBean.javaClass Inherited Mapped property test bean.
MappedPropertyChildInterface.javaInterface
MappedPropertyDescriptor.javaClass A MappedPropertyDescriptor describes one mapped property.
MappedPropertyTestBean.javaClass
MappedPropertyTestCase.javaClass
MappedPropertyTestInterface.javaInterface
MethodUtils.javaClass

Utility reflection methods focussed on methods in general rather than properties in particular.

MethodUtilsTestCase.javaClass
MutableDynaClass.javaInterface

A specialized extension to DynaClass that allows properties to be added or removed dynamically.

WARNING - No guarantees that this will be in the final APIs ...

NestedNullException.javaClass Thrown to indicate that the Bean Access Language cannot execute query against given bean since a nested bean referenced is null.
NestedTestBean.javaClass Specialist test bean for complex nested properties.
PassTestException.javaClass Just a runtime exception.
PrimitiveBean.javaClass
PropertyUtils.javaClass

Utility methods for using Java Reflection APIs to facilitate generic property getter and setter operations on Java objects.

The implementations for these methods are provided by PropertyUtilsBean. For more details see PropertyUtilsBean .


author:
   Craig R.
PropertyUtilsBean.javaClass Utility methods for using Java Reflection APIs to facilitate generic property getter and setter operations on Java objects.
PropertyUtilsBenchCase.javaClass JUnit Test Case containing microbenchmarks for PropertyUtils.
PropertyUtilsTestCase.javaClass

Test Case for the PropertyUtils class.

PropsFirstPropertyUtilsBean.javaClass A PropertyUtilsBean which customises the behaviour of the setNestedProperty and getNestedProperty methods to look for simple properties in preference to map entries.
ResultSetDynaClass.javaClass

Implementation of DynaClass for DynaBeans that wrap the java.sql.Row objects of a java.sql.ResultSet. The normal usage pattern is something like:

 ResultSet rs = ...;
 ResultSetDynaClass rsdc = new ResultSetDynaClass(rs);
 Iterator rows = rsdc.iterator();
 while (rows.hasNext())  {
 DynaBean row = (DynaBean) rows.next();
 ...
ResultSetIterator.javaClass

Implementation of java.util.Iterator returned by the iterator() method of ResultSetDynaClass .

RowSetDynaClass.javaClass

Implementation of DynaClass that creates an in-memory collection of DynaBean s representing the results of an SQL query.

SonOfAlphaBean.javaClass
TestBean.javaClass General purpose test bean for JUnit tests for the "beanutils" component.
author:
   Craig R.
TestBeanPackageSubclass.javaClass This is a package private subclass of TestBean.
TestBeanPublicSubclass.javaClass This is a public subclass of TestBean.
TestResultSet.javaClass

Mock object that implements enough of java.sql.ResultSet to exercise the ResultSetDyaClass functionality.


author:
   Craig R.
TestResultSetMetaData.javaClass

Mock object that implements enough of java.sql.ResultSetMetaData to exercise the ResultSetDynaClass functionality.


author:
   Craig R.
ThrowExceptionConverter.javaClass Converter implementation that throws a PassTestException when convert is called.
WrapDynaBean.javaClass

Implementation of DynaBean that wraps a standard JavaBean instance, so that DynaBean APIs can be used to access its properties.

The most common use cases for this class involve wrapping an existing java bean.

WrapDynaBeanTestCase.javaClass

Test Case for the WrapDynaBean implementation class. These tests were based on the ones in PropertyUtilsTestCase because the two classes provide similar levels of functionality.


author:
   Craig R.
WrapDynaClass.javaClass

Implementation of DynaClass for DynaBeans that wrap standard JavaBean instances.

It is suggested that this class should not usually need to be used directly to create new WrapDynaBean instances.

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.