• 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);




  • 相关阅读:
    交换技术 天高地厚
    【转载】VirtualBox中双虚拟机安装部署OpenStack指南 天高地厚
    Redo log 刷入磁盘示意图 天高地厚
    分布式环境下session的存储的几个解决方案 天高地厚
    【转载】mysql 日志管理 天高地厚
    等待类型的分类 天高地厚
    android gamil.com登录设置
    android : Avoiding Memory Leaks
    用点数据包存你的绘图信息
    android 9patch (讲的很不错,相当全面:转)
  • 原文地址:https://www.cnblogs.com/kuyuyingzi/p/4266292.html
Copyright © 2020-2023  润新知