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

来源:互联网 发布:mac地址有什么用 编辑:程序博客网 时间:2024/05/18 01:09

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. }  



阅读全文
0 0