ITeye博客

改进BeanUtils支持DATE类型

hilor · 2008-11-30 22:30 · J2EE · Markdown

项目中经常要用到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)即可...

评论(2)

  1. #2 楼 · amuro_lei · 2012-03-27 14:19

    可以试试用PropertyUtils.copyProperties代替?

  2. #1 楼 · heyaron · 2010-08-07 13:07

    String p = (String)arg1;
    报错,谢谢。如果是date不能强制转换

评论功能维护中,当前仅展示历史评论。