packagecom.day09;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.HashMap;importjava.util.Locale;importjava.util.Map;importorg.apache.commons.beanutils.BeanUtils;importorg.apache.commons.beanutils.ConversionException;importorg.apache.commons.beanutils.ConvertUtils;importorg.apache.commons.beanutils.Converter;importorg.apache.commons.beanutils.locale.converters.DateLocaleConverter;importorg.junit.Test;/*** apache感觉Java的内省api写的太麻烦了,自己开发了一套api就是BeanUtils,大大的简化了内省操作Javabean的属性,提高了效率
*
*@authorAdministrator
**/
public classBeanUtilsDemo {/*** 使用BeanUtils来给属性设置
*
*@throwsException*/@Testpublic void setProperties() throwsException {
Student s= newStudent();//传入bean的对象,属性名,属性值即可
BeanUtils.setProperty(s, "age", 23);
System.out.println(s.getAge());
}/*** BeanUtils支持8中基本数据类型进行数据转换(从String转换到对应的八种基本数据类型)
*
*@throwsException*/@Testpublic void setPropertiesOnBaseDataType() throwsException {
String name= "zhangsan";
String password= "123456";
String age= "23";
Student s= newStudent();
BeanUtils.setProperty(s,"name", name);
BeanUtils.setProperty(s,"password", password);
BeanUtils.setProperty(s,"age", age);
System.out.println(s);
}/*** BeanUtis虽然支持8中基本类型,但是它可提供了注册转换器机制,可以让除8中基本类型之外的其他类型也可以自动转换
*
*@throwsException*/@Testpublic void setPropertiesOnDateType() throwsException {
String birthday= "1993-9-25";
Student s= newStudent();//为了让日期赋值到bean的属性上,我们需要给Date注册一个日期转换器
ConvertUtils.register(newConverter() {
@OverridepublicObject convert(Class type, Object value) {if (value == null) {return null;
}if (!(value instanceofString)) {throw new ConversionException("只支持String类型");
}
String str=(String) value;if ("".equals(str.trim())) {return null;
}
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");try{returnsdf.parse(str);
}catch(ParseException e) {throw new RuntimeException(e);//要带上e,因为异常链不能断
}
}
}, Date.class);
BeanUtils.setProperty(s,"birthday", birthday);
System.out.println(s.getBirthday());
}/*** BeanUtis虽然支持8中基本类型,但是它可提供了注册转换器机制,可以让除8中基本类型之外的其他类型也可以自动转换
*
*@throwsException*/@Testpublic void setPropertiesOnDateType2() throwsException {
Student s= newStudent();
String birthday= "1993-09-25";//为了让日期赋值到bean的属性上,我们需要给Date注册一个日期转换器,而BanUtils框架也为我们提供了一个日期转换器
ConvertUtils.register(new DateLocaleConverter(Locale.CHINESE, "yy-MM-dd"), Date.class);
BeanUtils.setProperty(s,"birthday", birthday);
System.out.println(s.getBirthday());
}/*** 从map集合上做数据的映射
*
*@throwsException
*@throwsIllegalAccessException*/@Testpublic void setPropertiesOnMap() throwsIllegalAccessException, Exception {
Student s= newStudent();
Map map = new HashMap();//这里同样要注册一个日期转换器
ConvertUtils.register(new DateLocaleConverter(Locale.CHINESE, "yy-MM-dd"), Date.class);
map.put("name", "zhangsan");
map.put("age", "23");
map.put("birthday", "1993-9-25");
BeanUtils.populate(s, map);
System.out.println(s);
}
}