3.18. Creating a Dynamic Bean

Problem

You need to be able to create a bean dynamically at runtime.

Solution

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

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.