当用到BeanUtils的populate、copyProperties方法或者getProperty,setProperty方法其实都会调用convert进行转换
但自带的Converter只支持一些基本的类型,如果要转化为其他类型就要自己定义转化器并注册
自定义转换器只要实现BeanUtils的Converter接口,再 用ConverterUtils.register()方法进行注册即可
下面这个是Date转String()
</pre></div><div style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">下面以String转Date类型为例</div><div style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><pre code_snippet_id="1852034" snippet_file_name="blog_20160826_2_7128891" name="code" class="java">public class diyConverter {
@Test
public void test()
{
People people = new People();
Map<String, String> map=new HashMap<String,String>();
map.put("name", "chenny");
map.put("age", "20");
map.put("birth","2010-10-10 11:20:30");
/**
* ConvertUtils.regiser(Converter,clazz)
* 第一个参数为转换器
* 第二个参数为要转换的类型
*
*/
ConvertUtils.register(new Converter() {
public Object convert(Class arg0, Object arg1) {
//首先判断arg1是不是string类型
if(!(arg1 instanceof String))
{
throw new RuntimeException();
}
String str=(String) arg1;
//判断字符串是否为空或""字符串
if(str==null||str.trim().length()==0)
return null;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date;
try {
date = format.parse(str);
return date;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException();
}
}
}, Date.class);
try {
BeanUtils.populate(people, map);
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(people);
}
}
下面这个是Date转String()
需要注意的是目标类型是String,所以单有其他基本类型要转换String时,也会用这个转换器,所以要给其他非Date类型对象留一个出口
public class diyConverter {
@Test
public void test() throws IllegalAccessException, InvocationTargetException
{
Student student = new Student();
Map<String, Object> map=new HashMap<String,Object>();
map.put("name", "隔壁老王");
map.put("age", 25);
map.put("birth", new Date());
//注册一个日期转换器
ConvertUtils.register(new Converter() {
@Override
public String convert(Class arg0, Object arg1) {
//先判断原始类型是否为Date
if(!(arg1 instanceof Date))
//重点:如果不是Date,要给其他基本数据类型留一个出口
return (String) arg1;
//再判断是否为空
Date date=(Date)arg1;
if(date==null)
return null;
//转型
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String str = format.format(date);
return str;
}
}, String.class);
//javabean赋值操作
BeanUtils.copyProperties(student, map);
System.out.println(student);
}
}