Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting field value to null with reflection

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?

like image 863
Jaanus Avatar asked Oct 08 '13 13:10

Jaanus


2 Answers

I managed to do it with standard reflection.

java.lang.reflect.Field prop = object.getClass().getDeclaredField("deliveryDate");
prop.setAccessible(true);
prop.set(object, null);
like image 138
Jaanus Avatar answered Oct 02 '22 07:10

Jaanus


It can be done by simple trick

Method setter;
setter.invoke(obj, (Object)null);
like image 23
Błażej Avatar answered Oct 02 '22 09:10

Błażej