java date赋空值_使用BeanUtils时,Date类型值为空的解决方法

使用BeanUtils时,Date类型值为空的解决方法

org.apache.commons.beanutils.ConversionException: No value specified for 'Date'

现在系统里原先不出错的地方老是出现以上这个错误,不知道什么原因。也都是BeanUtils.copyProperties(teaInfo, infoForm);这种语句出的错。

package com.fish.util;

import org.apache.commons.beanutils.ConvertUtils;

import org.apache.commons.beanutils.BeanUtils;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import java.util.HashMap;

import java.util.Map;

import java.lang.reflect.*;

public final class BeanUtilEx

extends BeanUtils {

private static Map cache = new HashMap();

private static Log logger = LogFactory.getFactory().getInstance(BeanUtilEx.class);

private BeanUtilEx() {

}

static {

//注册sql.date的转换器,即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空

ConvertUtils.register(new SqlDateConverter(), java.util.Date.class);

//ConvertUtils.register(new SqlTimestampConverter(), java.sql.Timestamp.class);

//注册util.date的转换器,即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空

ConvertUtils.register(new UtilDateConverter(), java.util.Date.class);

}

public static void copyProperties(Object target, Object source) throws

InvocationTargetException, IllegalAccessException {

//update bu zhuzf at 2004-9-29

//支持对日期copy

org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);

}

}

项目中经常要用到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;

}

}

}

}

posted on 2011-06-23 09:39 墙头草 阅读(24470) 评论(2)  编辑  收藏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值