3.18. Creating a Dynamic Bean
Use a DynaBean. You can create a DynaBean with an arbitrary set of properties at runtime, and the resulting DynaBean object will function properly with all Commons BeanUtils utilities, such as PropertyUtils. The following example demonstrates the use of a BasicDynaBean to model a politician:
import java.util.*;
import org.apache.commons.beanutils.*;
DynaProperty[] beanProperties = new DynaProperty[]{
new DynaProperty("name", String.class),
new DynaProperty("party", Party.class),
new DynaProperty("votes", Long.class)
};
BasicDynaClass politicianClass =
new BasicDynaClass("politician", BasicDynaBean.class, props);
DynaBean politician = politicianClass.newInstance( );
// Set the properties via DynaBean
politician.set( "name", "Tony Blair" );
politician.set( "party", Party.LABOUR );
politician.set( "votes", new Long( 50000000 ) );
// Set the properties with PropertyUtils
PropertyUtils.setProperty( politician, "name", "John Major" );
PropertyUtils.setProperty( politician, "party", Party.TORY );
PropertyUtils.setProperty( politician, "votes", new Long( 50000000 ) );
In this code, the properties of the politician bean are set using two different methods. The first method is to manipulate properties via the DynaBean interface, and the second method involves using PropertyUtils.setProperty( ). Both regions of code accomplish the same goal, and PropertyUtils was included to emphasize the fact that most utilities in BeanUtils will understand how to work with DynaBean implementations.
DynaBean objects come in handy when your system uses beans to represent a data model. Since a bean is just a collection of properties, you can avoid having to maintain a bean class by automatically generating a bean from a description of the objects and properties; for example, a complex data model could be described in an XML document, and a utility would parse such a document and create a number of DynaClass objects at runtime.
A DynaBean contains the methods listed in Table 3-2. There are methods to get and set indexed and mapped properties, and two operations—remove() and contains( )—allow you to manipulate the contents of a Map property.
Table 3-2. Methods available on a DynaBean
|
Method |
Description |
|---|---|
|
|
Retrieves a simple bean property |
|
|
Retrieves an indexed been property |
|
|
Retrieves a mapped bean property |
|
|
Sets a simple bean property |
|
|
Sets an indexed bean property |
|
|
Sets a mapped bean property |
|
|
Removes a key from a mapped bean property |
|
|
Tests a map property for the presence of a key |
Chapter 6 combines the power of Commons Digester and Commons BeanUtils to create a utility that reads in bean definitions from an XML document. A data model is described using an XML document, and it is realized into a set of DynaClass objects.
Chapter 12 discusses the power of Commons BeanUtils as it relates to working with a database. A ResultSetDynaClass enables you to wrap a JDBC ResultSet.