当用到BeanUtils的populate、copyProperties方法或者getProperty,setProperty方法其实都会调用convert进行转换
但Converter只支持一些基本的类型,甚至连java.util.Date类型也不支持。而且它比较笨的一个地方是当遇到不认识的类型时,居然会抛出异常来。
这个时候就需要给类型注册转换器。比如:意思是所以需要转成Date类型的数据都要通过DateLocaleConverter这个转换器的处理。
ConvertUtils.register(new DateLocaleConverter(), Date.class);
示例:
ConvertUtils除了给指定类型注册转换器外,还可以将数据转换为指定类型
这个时候就需要给类型注册转换器。比如:意思是所以需要转成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);