I managed to do it with standard reflection.
java.lang.reflect.Field prop = object.getClass().getDeclaredField("deliveryDate");
prop.setAccessible(true);
prop.set(object, null);
Question
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?
Solution
I managed to do it with standard reflection.
java.lang.reflect.Field prop = object.getClass().getDeclaredField("deliveryDate");
prop.setAccessible(true);
prop.set(object, null);
OTHER TIPS
It can be done by simple trick
Method setter;
setter.invoke(obj, (Object)null);
A similar complaint (and workaround) was posted in the bug tracker for BeanUtils. See https://issues.apache.org/jira/browse/BEANUTILS-387
Book book = new Book();
Class<?> c = book.getClass();
Field chap = c.getDeclaredField("chapters");
chap.setLong(book, 12)
System.out.println(chap.getLong(book));
[Oracle Offical Source] https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html