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

被折叠的 条评论
为什么被折叠?



