现象:转换Double字段NULL值字段返回的是0.0
解决方法:注册数值转换器默认值,如果自定义新的beanutils直接放新类中。
static { ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new ShortConverter(null), Short.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); }
相关:在commons.beanutils.jar
1. package org.apache.commons.beanutils.ConvertUtils;
public static void register(Converter converter, Class clazz) {
ConvertUtilsBean.getInstance().register(converter, clazz);
}
2.org.apache.commons.beanutils.converters.DoubleConverter;
public DoubleConverter(Object defaultValue) {
super(true, defaultValue);
}
3.BeanUtils(本次使用的BeanUtils自定义继承自原提供的类的一个转换函数,字段是Double类型),调用转换器
....
org.apache.commons.beanutils.BeanUtils.populate(bean, properties);
...
package org.apache.commons.beanutils.BeanUtilsBean(类).populate(方法);
...
package org.apache.commons.beanutils.BeanUtilsBean.setProperty(bean, name, entry.getValue());
public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) .... // Resolve any nested expression to get the actual target bean .... // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property Class type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the property type .... // Convert the specified value to the required type Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array .... } else if (type.isArray()) { // Indexed value into array .... } else { // Value into scalar if (value instanceof String) { newValue = getConvertUtils().convert((String) value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type); } else { //测试数值型字段为null值时,为字段设置默认值 newValue = convert(value, type); } } // Invoke the setter method try { getPropertyUtils().setProperty(target, name, newValue); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } }
...
....
package org.apache.commons.beanutils.converters.AbstractConverter;

