Saturday, March 19, 2011

How to configure the way BeanUtils converts null value

By default BeanUtils.setProperty always assign a default value for null. For an instance, if the property's type being set is Integer then you will get 0. This could be the behavior that many do not expect, for example you use Struts and you have an entry form with a number field. And you're expecting that if the user leave it empty, you would like to display it as empty later on.
BeanUtils utilized by Struts will fill the field as 0 instead of leaving it null.

Underneath BeanUtils is utilizing a ConverterUtils to convert the value before setting it to the property. Therefore to change this behavior all we need to do is to register a new IntegerConverter to ConverterUtils, thereby overriding the default converter used.

e.g.
ConvertUtils.register(new IntegerConverter(null), Integer.class);

The same thing you should do for other types as needed.

If you indeed configure the converter, you might want to read this.

1 comment:

Anonymous said...

Thanks! This was a big help.