ConvertUtils.reqister注册转换器

当用到BeanUtils的populate、copyProperties方法或者getProperty,setProperty方法其实都会调用convert进行转换

但Converter只支持一些基本的类型,甚至连java.util.Date类型也不支持。而且它比较笨的一个地方是当遇到不认识的类型时,居然会抛出异常来。
这个时候就需要给类型注册转换器。比如:意思是所以需要转成Date类型的数据都要通过DateLocaleConverter这个转换器的处理。
ConvertUtils.register(new DateLocaleConverter(), Date.class);
示例:


 
  1. import java.util.Date;  
  2.   
  3. public class Person {  
  4.     private String name;  
  5.     private int age;  
  6.     private Date birth;  
  7.     public String getName() {  
  8.         return name;  
  9.     }  
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.     public int getAge() {  
  14.         return age;  
  15.     }  
  16.     public void setAge(int age) {  
  17.         this.age = age;  
  18.     }  
  19.     public Date getBirth() {  
  20.         return birth;  
  21.     }  
  22.     public void setBirth(Date birth) {  
  23.         this.birth = birth;  
  24.     }  
  25. }  

test1没有给Date注册转换器,抛出ConversionException异常,test2没有异常


 
  1. @Test  
  2.     public void test1() throws Exception {  
  3.         Map map = new HashMap();  
  4.         map.put("name", "xiazdong");  
  5.         map.put("age", "20");  
  6.         map.put("birth", "2010-10-10");  
  7.         Person p = new Person();  
  8.         BeanUtils.populate(p, map);  
  9.         System.out.println(p.getAge());  
  10.         System.out.println(p.getBirth().toLocaleString());  
  11.     }  

 
  1. @Test  
  2.     public void test2() throws Exception {  
  3.         Map map = new HashMap();  
  4.         map.put("name", "xiazdong");  
  5.         map.put("age", "20");  
  6.         map.put("birth", "2010-10-10");  
  7.         ConvertUtils.register(new DateLocaleConverter(), Date.class);  
  8.         Person p = new Person();  
  9.         BeanUtils.populate(p, map);  
  10.         System.out.println(p.getAge());  
  11.         System.out.println(p.getBirth().toLocaleString());  
  12.     }  


ConvertUtils除了给指定类型注册转换器外,还可以将数据转换为指定类型


 
    1. String[] values = new String[]{};  
    2. (long[])ConvertUtils.convert(values, long.class);  
posted @ 2018-02-26 15:18  keepup~  阅读(177)  评论(0编辑  收藏  举报