简体   繁体   English

使用反射将字段值设置为null

[英]Setting field value to null with reflection

I am setting a variable value to null, but having problem with it: 我将变量值设置为null,但有问题:

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. 基本上它试图将java.sql.Timestamp值设置为null,但由于某种原因它不起作用。

On the other hand, I am using reflection wrapper BeanUtils( http://commons.apache.org/proper/commons-beanutils/ ), maybe this is possible with plain reflection? 另一方面,我使用反射包装器BeanUtils( http://commons.apache.org/proper/commons-beanutils/ ),也许这可以用简单的反射?

I managed to do it with standard reflection. 我设法用标准反射做到了。

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

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. 在BeanUtils的bug跟踪器中发布了类似的投诉(和解决方法)。 See https://issues.apache.org/jira/browse/BEANUTILS-387 请参阅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 [Oracle官方来源] https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM