我将变量值设置为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
这是错误:
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)
基本上它试图将java.sql.Timestamp值设置为null,但由于某种原因它不起作用。
另一方面,我正在使用反射包装器BeanUtils(http://commons.apache.org/proper/commons-beanutils/),也许这可以通过简单的反射来实现?
答案 0 :(得分:6)
我设法用标准反射来做。
java.lang.reflect.Field prop = object.getClass().getDeclaredField("deliveryDate");
prop.setAccessible(true);
prop.set(object, null);
答案 1 :(得分:2)
可以通过简单的技巧
完成Method setter;
setter.invoke(obj, (Object)null);
答案 2 :(得分:1)
类似的投诉(和解决方法)已发布在BeanUtils的错误跟踪器中。见https://issues.apache.org/jira/browse/BEANUTILS-387
答案 3 :(得分:0)
Book book = new Book();
Class<?> c = book.getClass();
Field chap = c.getDeclaredField("chapters");
chap.setLong(book, 12)
System.out.println(chap.getLong(book));
[Oracle官方资源] https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html