ConvertUtils.register

當用到BeanUtils的populate、copyProperties方法或者getProperty,setProperty方法其實都會調用convert進行轉換
但Converter只支持一些基本的類型,甚至連java.util.Date類型也不支持。而且它比較笨的一個地方是當遇到不認識的類型時,居然會拋出異常來。
這個時候就需要給類型註冊轉換器。比如:意思是所以需要轉成Date類型的數據都要通過DateLocaleConverter這個轉換器的處理
ConvertUtils.register(new DateLocaleConverter(), Date.class);
示例:
    import java.util.Date;  
      
    public class Person {  
        private String name;  
        private int age;  
        private Date birth;  
        public String getName() {  
            return name;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        public int getAge() {  
            return age;  
        }  
        public void setAge(int age) {  
            this.age = age;  
        }  
        public Date getBirth() {  
            return birth;  
        }  
        public void setBirth(Date birth) {  
            this.birth = birth;  
        }  
    }  


test1沒有給Date註冊轉換器,拋出ConversionException異常,test2沒有異常

    @Test  
        public void test1() throws Exception {  
            Map map = new HashMap();  
            map.put("name", "xiazdong");  
            map.put("age", "20");  
            map.put("birth", "2010-10-10");  
            Person p = new Person();  
            BeanUtils.populate(p, map);  
            System.out.println(p.getAge());  
            System.out.println(p.getBirth().toLocaleString());  
        }  



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

ConvertUtils除了給指定類型註冊轉換器外,還可以將數據轉換爲指定類型

String[] values = new String[]{};  
(long[])ConvertUtils.convert(values, long.class);  

發佈了54 篇原創文章 · 獲贊 18 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章