Setting field value to null with reflection

Jaanus picture Jaanus · Oct 8, 2013 · Viewed 13.2k times · Source

I am setting a variable value to null, but having problem with it:

public class BestObject {
    private Timestamp deliveryDate;
    public void setDeliveryDate(Timestamp deliveryDate) {
         this.deliveryDate = deliveryDate;
    }
}

BeanUtils.setProperty(new BestObject(), "deliveryDate", null); // usually the values are not hardcoded, they come from configuration etc

This is the error:

org.apache.commons.beanutils.ConversionException: No value specified
    at org.apache.commons.beanutils.converters.SqlTimestampConverter.convert(SqlTimestampConverter.java:148)
    at org.apache.commons.beanutils.ConvertUtils.convert(ConvertUtils.java:379)
    at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:999)

Basically it is trying to set a java.sql.Timestamp value to null, but it is not working for some reason.

On the other hand, I am using reflection wrapper BeanUtils(http://commons.apache.org/proper/commons-beanutils/), maybe this is possible with plain reflection?

Answer

Jaanus picture Jaanus · Oct 9, 2013

I managed to do it with standard reflection.

java.lang.reflect.Field prop = object.getClass().getDeclaredField("deliveryDate");
prop.setAccessible(true);
prop.set(object, null);