zoukankan      html  css  js  c++  java
  • 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);




  • 相关阅读:
    组合容斥计数技巧
    [BZOJ3456]城市规划:DP+NTT+多项式求逆
    [BZOJ4456][ZJOI2016]旅行者:分治+最短路
    [51nod1383&1048]整数分解为2的幂:DP
    [BZO3572][HNOI2014]世界树:虚树+倍增
    树上最小权链覆盖:可并堆
    [BZOJ4237]稻草人:CDQ分治+单调栈
    [BZOJ3453]tyvj 1858 XLkxc:拉格朗日插值
    [BZOJ5463][APIO2018]铁人两项:Tarjan+圆方树
    [BZOJ4695]最假女选手:segment tree beats!
  • 原文地址:https://www.cnblogs.com/kuyuyingzi/p/4266292.html
Copyright © 2011-2022 走看看