Java 使用反射将字段值设置为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19248529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting field value to null with reflection
提问by Jaanus
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/),也许这可以通过简单的反射实现?
采纳答案by Jaanus
I managed to do it with standard reflection.
我设法用标准反射做到了。
java.lang.reflect.Field prop = object.getClass().getDeclaredField("deliveryDate");
prop.setAccessible(true);
prop.set(object, null);
回答by bstempi
A similar complaint (and workaround) was posted in the bug tracker for BeanUtils. See https://issues.apache.org/jira/browse/BEANUTILS-387
在 BeanUtils 的错误跟踪器中发布了类似的投诉(和解决方法)。见https://issues.apache.org/jira/browse/BEANUTILS-387
回答by B?a?ej
It can be done by simple trick
它可以通过简单的技巧来完成
Method setter;
setter.invoke(obj, (Object)null);
回答by Oguzhan Cevik
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