代码如下 导包 org.apache.commons.beanutils
package com.util;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.ConvertUtils;
/**
* 实体拷贝时候关于Date为null 的解决
* @author lenovo
*
*/
public class BeanUtilEx {
private BeanUtilEx() {}
static {
// 注册sql.date的转换器,即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空
ConvertUtils.register(new org.apache.commons.beanutils.converters.SqlDateConverter(null), java.sql.Date.class);
ConvertUtils.register(new org.apache.commons.beanutils.converters.SqlDateConverter(null), java.util.Date.class);
ConvertUtils.register(new org.apache.commons.beanutils.converters.SqlTimestampConverter(null),java.sql.Timestamp.class);
// 注册util.date的转换器,即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空
}
public static void copyProperties(Object target, Object source) throws IllegalAccessException, InvocationTargetException {
// 支持对日期copy BeanUtils.copyProperties(a, b); b拷贝到a
org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
}
}
测试方法如下:
package com.testCode;
import java.lang.reflect.InvocationTargetException;
import com.entity.Area;
import com.util.BeanUtilEx;
public class Test1 {
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
Area taregt = new Area();
Area source = new Area();
source.setId(1);
source.setCity("成都");
source.setProvince("");
//BeanUtils.copyProperties(a, b); b拷贝到a
BeanUtilEx.copyProperties(taregt, source);
System.out.println(taregt);
}
}
控制台输出如下:
Area [id=1, province=, city=成都, district=null, postcode=null, abbrecode=null, citycode=null]
解决的实体拷贝属性NULL的问题