改进BeanUtils支持DATE类型

项目中经常要用到BeanUtils, 可惜的是BeanUtils只支持基本数据类型转换, 最麻烦的是连比较常用的DATE类型都不支持, 无奈之下只好改装..

实际上只需要扩展Converter, 增加一个Converter接口的实例DateConvert, 在内部写好转换方法并注册就OK.. 上代码

 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.Converter;

/**
 *
 * @author lucas
 */
public class DateConvert implements Converter {

    public Object convert(Class arg0, Object arg1) {
        String p = (String)arg1;
        if(p== null || p.trim().length()==0){
            return null;
        }   
        try{
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return df.parse(p.trim());
        }
        catch(Exception e){
            try {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                return df.parse(p.trim());
            } catch (ParseException ex) {
                return null;
            }
        }
        
    }

}
 然后再写一个BeanUtilsEx继承BeanUtils, 并在里面注册DateConvert

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

/**
 *
 * @author lucas
 */
public class BeanUtilsEx extends BeanUtils {
    static {
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        ConvertUtils.register(new DateConvert(), java.sql.Date.class);
    }

    public static void copyProperties(Object dest, Object orig) {
        try {
            BeanUtils.copyProperties(dest, orig);
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }
}
 
BeanUtilsEx.copyProperties(dest, orig)即可... 

你可能感兴趣的:(java,apache,sql)