使用BeanUtils設置/讀取屬性的值以及默認支持的自動轉化:
@Test
//使用BeanUtils設置/讀取屬性的值以及自動轉化
public void test1() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
Person p=new Person();
//使用BeanUtils設置屬性的值
BeanUtils.setProperty(p, "username", "李四");
//使用BeanUtils讀取屬性的值
System.out.println(BeanUtils.getProperty(p, "username"););
//類型不同依然可以自動轉化,BeanUtils默認支持八種基本類型的轉換
BeanUtils.setProperty(p,"age", "123");
System.out.println(p.getAge());
}
注冊已有的轉化器來完成復雜類型的自動轉化:
@Test
//注冊已有的轉化器來完成復雜類型的自動轉化
public void test3() throws IllegalAccessException, InvocationTargetException{
Person p=new Person();
String birthday="1995-05-05";
//注冊Apache提供的時間轉換器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.setProperty(p, "birthday", birthday);
System.out.println(p.getBirthday());
}
Apache已有的時間轉化器中不能很好地過濾空字符串,若待轉換字符串為空則會拋出異常;而現實業務非常復雜,Apache無法提供給我們所有的類型轉化方法,需要時我們可以注冊自己需要的轉換器完成業務需求。
注冊自己的轉換器完成時間轉化:
@Test
//注冊自己的轉換器完成時間轉化
public void test2() throws IllegalAccessException, InvocationTargetException{
Person p=new Person();
String birthday="1995-05-05";
//為了日期可以賦值到bean的屬性,我們給benUtils注冊日期轉換器
ConvertUtils.register(new Converter(){
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object convert(Class type,Object value){
if(value==null){
return null;
}
if(!(value instanceof String)){
throw new ConversionException("只支持String類型的轉換");
}
String str=(String) value;
if(str.trim().equals("")){
return null;
}
SimpleDateFormat dateformate=new SimpleDateFormat("yyyy-MM-dd");
try {
return dateformate.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}, Date.class);
BeanUtils.setProperty(p, "birthday", birthday);
System.out.println(p.getBirthday());
}
直接使用map對象填充類:
@Test
//直接使用map對象填充類
public void test4() throws Exception{
HashMap<String, String> map=new HashMap<String,String>();
map.put("username","李四");
map.put("password","lisi");
map.put("age","26");
map.put("birthday","1990-05-05");
ConvertUtils.register(new DateLocaleConverter() , Date.class);
Person p=new Person();
BeanUtils.populate(p, map);
System.out.println(p.getUsername());
System.out.println(p.getPassword());
System.out.println(p.getAge());
System.out.println(p.getBirthday());
}