DateConverter does not support default String to 'Date' conversion.的處理

DateConverter does not support default String to 'Date' conversion.的處理


在使用beanutils工具類封裝javabean時,beanUtils不提供直接將字符串轉換成Date(java.util.Date)數據類型的方法,

所以會出現下面警告:




或者類似下面異常:

org.apache.commons.beanutils.ConversionException: DateConverter does not support default String to 'Date' conversion.


解決辦法:

1.自己寫個轉換器的代碼塊

try {

			ConvertUtils.register(new Converter() {//註冊一個日期轉換器

				public Object convert(Class type, Object value) {
					Date date1 =null; 
					if(value instanceof String){ 
						String date = (String) value;
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
						try {
							date1 = sdf.parse(date);
						} catch (ParseException e) {
							e.printStackTrace(); 
						} 
					} 
					return date1; 
				}
			}, Date.class);


2.哈哈!beanutil這個工具類源碼裏有提供DateLocaleConverter這個類做註冊的轉化器

ConvertUtils.register(new DateLocaleConverter(), Date.class);




現實工具類方法爲:


[java] view plain copy
  1. public static void transMap2Bean(Map<String, Object> map, Object obj) {    
  2.     //ConvertUtils.register(new DateLocaleConverter(), Date.class);  
  3.     ConvertUtils.register(new Converter()    
  4.     {    
  5.              
  6.   
  7.         @SuppressWarnings("rawtypes")    
  8.         @Override    
  9.         public Object convert(Class arg0, Object arg1)    
  10.         {    
  11.             System.out.println("註冊字符串轉換爲date類型轉換器");    
  12.             if(arg1 == null)    
  13.             {    
  14.                 return null;    
  15.             }    
  16.             if(!(arg1 instanceof String))    
  17.             {    
  18.                 throw new ConversionException("只支持字符串轉換 !");    
  19.             }    
  20.             String str = (String)arg1;    
  21.             if(str.trim().equals(""))    
  22.             {    
  23.                 return null;    
  24.             }    
  25.                  
  26.             SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
  27.                  
  28.             try{    
  29.                 return sd.parse(str);    
  30.             }    
  31.             catch(ParseException e)    
  32.             {    
  33.                 throw new RuntimeException(e);    
  34.             }    
  35.                  
  36.         }    
  37.              
  38.     }, java.util.Date.class);    
  39.     if (map == null || obj == null) {    
  40.         return;    
  41.     }    
  42.     try {    
  43.         BeanUtils.populate(obj, map);    
  44.     } catch (Exception e) {    
  45.         System.out.println("Map<String,Object>轉化Bean異常:" + e);    
  46.     }    
  47. }  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章