首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

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

2012-08-02 
使用BeanUtils时,Date类型值为空的解决方法解决办法参考:http://hi.baidu.com/fcp_bd/blog/item/0e632783c

使用BeanUtils时,Date类型值为空的解决方法
解决办法参考:http://hi.baidu.com/fcp_bd/blog/item/0e632783c08836a50cf4d2c4.html/cmtid/53484428cab979f399250ad7

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

package com.asl.cityu.common;import java.text.ParseException;import java.text.SimpleDateFormat;import org.apache.commons.beanutils.Converter;public class DateConvert implements Converter {private static String dateFormatStr = "yyyy/MM/dd";private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateFormatStr);private static String dateLongFormatStr = dateFormatStr+" HH:mm:ss";private static SimpleDateFormat dateTimeLongFormat = new SimpleDateFormat(dateLongFormatStr);public Object convert(Class arg0, Object arg1) {System.out.println(arg1.getClass().getName()+"="+arg1.toString());String className = arg1.getClass().getName();//java.sql.Timestampif ("java.sql.Timestamp".equalsIgnoreCase(className)) {try {SimpleDateFormat df = new SimpleDateFormat(dateFormatStr + " HH:mm:ss");return df.parse(dateTimeLongFormat.format(arg1));} catch (Exception e) {try {SimpleDateFormat df = new SimpleDateFormat(dateFormatStr);return df.parse(dateTimeFormat.format(arg1));} catch (ParseException ex) {e.printStackTrace();return null;}}}else{//java.util.Date,java.sql.DateString p = (String) arg1;if (p == null || p.trim().length() == 0) {return null;}try {SimpleDateFormat df = new SimpleDateFormat(dateFormatStr + " HH:mm:ss");return df.parse(p.trim());} catch (Exception e) {try {SimpleDateFormat df = new SimpleDateFormat(dateFormatStr);return df.parse(p.trim());} catch (ParseException ex) {e.printStackTrace();return null;}}}}public static String formatDateTime(Object obj) {if (obj != null)return dateTimeFormat.format(obj);elsereturn "";}public static String formatLongDateTime(Object obj) {if (obj != null)return dateTimeLongFormat.format(obj);elsereturn "";}}






package com.asl.cityu.common;import java.lang.reflect.InvocationTargetException;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConvertUtils;public class ExtBeanUtils extends BeanUtils {static {ConvertUtils.register(new DateConvert(), java.util.Date.class);ConvertUtils.register(new DateConvert(), java.sql.Date.class);ConvertUtils.register(new DateConvert(), java.sql.Timestamp.class);}public static void copyProperties(Object dest, Object orig) {try {BeanUtils.copyProperties(dest, orig);} catch (IllegalAccessException ex) {ex.printStackTrace();} catch (InvocationTargetException ex) {ex.printStackTrace();}}}



最后调用:
ExtBeanUtils.copyProperties(toObject, fromObject);

热点排行