10

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?

Jaanus
  • 16,161
  • 49
  • 147
  • 202
  • Your example is not compilable. Where does 'myObject' come from? Please edit your code so we can tell what's going on. (Show myObject's instantiation) – Rebecca Nelson Oct 08 '13 at 13:23
  • @TFNelson sorry, myObject is the POJO, where deliveryDate is. I will try to edit to make it better. – Jaanus Oct 08 '13 at 13:26

4 Answers4

16

I managed to do it with standard reflection.

java.lang.reflect.Field prop = object.getClass().getDeclaredField("deliveryDate");
prop.setAccessible(true);
prop.set(object, null);
Jaanus
  • 16,161
  • 49
  • 147
  • 202
2

It can be done by simple trick

Method setter;
setter.invoke(obj, (Object)null);
Błażej
  • 151
  • 1
  • 7
1

A similar complaint (and workaround) was posted in the bug tracker for BeanUtils. See https://issues.apache.org/jira/browse/BEANUTILS-387

bstempi
  • 2,023
  • 1
  • 15
  • 27
1
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

Oguzhan Cevik
  • 638
  • 8
  • 18