Simple DynaBean example

This example shows the basic steps to create a DynaBean using Apache Commons Beanutils. A DynaBean is a Java object that supports properties whose names and data types, as well as values, may be dynamically modified.

Another difference compared to an ordinary JavaBean is that we don’t have to provide getters and setter for the properties.
The properties of a DynaBean is set in a DynaClass, so the best way of creating a DynaBean is to create a DynaClass with the appropriate properties and then call newInstance on the class to get the DynaBean instance. A DynaClass is a simulation of the functionality of java.lang.Class for classes implementing the DynaBean interface.

The Beanutil package provides interfaces for DynaBean and DynaClass which may be implemented in your custom class. However, it also provides classes with minimum implementation of these interfaces. These classes are named BasicDynaBean and BasicDynaClass.

In the example below we first create a BasicDynaClass to which we send in the name of our dynamically created class, in this case ‘Car’. We could also specify a certain DynaClass as the second parameter, but we won’t use a custom one so we just type null. The third parameter is an array of properties that our dynamic class will contain. In this case we only have one property which is ‘numberOfWheels’ and is of type Integer. There could of course be any number of properties in the array.

Then we create our DynaBean instance and use the set method to actually put a value to that property. Finally we try to fetch that property by calling the get method and print out the value, and we also print out the name of the class that this DynaBean is created from.

The output from the code above is:

Search for more Java info on this site here:
Custom Search

Please type any questions here.