Setting field value to null with reflection

14,313

Solution 1

I managed to do it with standard reflection.

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

Solution 2

It can be done by simple trick

Method setter;
setter.invoke(obj, (Object)null);

Solution 3

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

Solution 4

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

Share:
14,313
Jaanus
Author by

Jaanus

Doing C#, Java 50-50. SOreadytohelp

Updated on July 21, 2022

Comments

  • Jaanus
    Jaanus almost 2 years

    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?

  • Sham Fiorin
    Sham Fiorin almost 5 years
    Very good exemple, that with that we can create a generic method for set in a field