現象:轉換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;

