Thursday, January 14, 2010

Setting Null value (reflectively) using Apache Common’s PropertyUtils

If you have a requirement to set a Null value (reflectively) to a property of an object using Apache Commons than following method won’t work for you:

BeanUtils.setProperty(Object bean, String propertyName, Object value);

And neither does this one:

PropertyUtils.setProperty(Object bean, String propertyName, Object value);

The reason is that both method uses ConvertUtils to convert values of source type to a destination type. The default set of converters which are registered with BeanUtils have a default value specified and this is why you can’t set a null value using default settings. If you want null values to be set then you need to register converter implementations for those types with a default value of null. So for example you would do something like...

ConvertUtils.register(new IntegerConverter(null), Integer.class);
ConvertUtils.register(new DoubleConverter(null), Double.class);

(Note: the "null" value in the constructors is the default value)

Alternatively, you can also achieve this by following statement:

PropertyUtils.getWriteMethod(PropertyUtils.getPropertyDescriptor(this,propertyName)).invoke(this, new Object[]{null});