Jakarta BeanUtils PropertyUtils
I recently had to work with the Jakarta BeanUtils project and found it really useful. I think of it as BeanUseful. The BeanUtils project allows you to easily manipulate a JavaBean object using the static methods from the PropertyUtils class. Here is a simple example of how to update a property value of a JavaBean. Imagine I have a simple Greeting JavaBean class with a single property message.
Greeting object = new Greeting(); object.setMessage("Hello"); // ... String greeting = (String)PropertyUtils .getSimpleProperty(object, "message"); PropertyUtils.setSimpleProperty( object, "message", greeting+", World!");
Of course, object is an instance of a JavaBean with a property named message.
PropertyUtils can also access an indexed method. Here is how you define an indexed property for a JavaBean:
public Item getItem(int index); public void setItem(int index, Item item);
And here is how you would access an index property using PropertyUtils:
int index = ...; String name = "item[" + index + "]"; Item item = (Item)PropertyUtils .getIndexedProperty(object, name);
In similar fashion, you can access a property that is mapped. Here is an example of how you define a mapped property in a JavaBean:
public Object getValue(String key); public void setValue(String key, Object item);
And here is how you would access a mapped property using PropertyUtils:
PropertyUtils.setMappedProperty( object, "value("+key+")", value);
The BeanUtils project and Java Reflection in general, is best used in a dynamic setting when you do not know the type of a bean at compile time; that is the strength of Java Reflection, which BeanUtils builds on.