Using the BeanMap class

This example shows how to use the BeanMap class of the Apache Commons Beanutils library. The BeanMap class is a Map implementation for JavaBeans, so instead of using getters and setters to work with the properties of the bean the common get and put methods of a Map is used instead (i.e. introspection). This also means that we can iterate over the keys, or property names, and get all property names and their values without really knowing the name of them.

This first example shows how to create a bean and use the ordinary get and set methods to set the property values. Then a BeanMap is created and the bean is added to it. Then we iterate over the keys (properties) of the bean twice. The first time to just print out the name of the properties and the second time to print out both name and value.

The output from the code above looks like this:

Instead of using the set and get methods of the Car class we could just simply create the bean and add it to the BeanMap. Then we can use the put method of the map to set the values of our properties:

The output from the code above is the same as earlier.
Below is the code for the JavaBean used in the examples above.

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

Please type any questions here.