Using Commons beanUtils I would like to know how to ask any converter say the Dateconverter to ignore null values and use null as default. As an example consider a public class,
public class X {
private Date date1;
private String string1;
//add public getters and setters
}
and my convertertest as,
public class Apache {
@Test
public void testSimple() throws Exception {
X x1 = new X(), x2 = new X();
x1.setString1("X");
x1.setDate1(null);
org.apache.commons.beanutils.BeanUtils.copyProperties(x2, x1);
//throws ConversionException
System.out.println(x2.getString1());
System.out.println(x2.getDate1());
}
}
The above 开发者_JAVA百科throws a NPE since the date happens to be null. This looks a very primitive scenario to me which should be handled by default (as in, I would expect x2 to have null value for date1). The doco tells me that I can ask the converter to do this. Can someone point me as to the best way for doing this ?
I dont want to get hold of the Converter and isUseDefault() to be true because then I have to do it for all Date, Enum and many other converters !
Apparently it looks like, there is a way to tell the ConvertUtils to not throw exceptions on null values which is achieved by calling
BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
The best solution is update to BeanUtils 1.9.0, since this problem is fixed as you can see here https://issues.apache.org/jira/browse/BEANUTILS-454
Maybe a little late but looks that you can register a DateConverter https://issues.apache.org/jira/browse/BEANUTILS-387
I recently ran into this issue and just converted my variable to a string to avoid this error and converted it back to a date when needed. Not the most elegant solution, but for simplicity and to avoid problems like this, it's a viable solution. The other caveat was that BeanUtils would fire off it's methods before my classes would load, so I opted for this rather than a more complicated solution to the problem using custom classloaders.
By the way, prior to verion 1.8.0, BeanUtils itself would ignore these null values.
See this link: No value specified for 'Date' when the field is a java.util.Date with a null value for a detailed explanation.
I am somewhat amazed that such a simple case as setting a null value in a bean, like this:
BeanUtils.setProperty(pojo, "date", null);
causes crashing behavior, as described above.
For what it's worth, here is my workaround:
import org.apache.commons.beanutils.BeanMap;
BeanMap beanMap = new BeanMap(pojo);
Method writeMethod = beanMap.getWriteMethod("date");
writeMethod.invoke(pojo, null);
精彩评论