public void test1()throws IlegallAccessException,InvocationTargetException{
Person p=new Person();
BeanUtils.setProperty(p,”name”,”xcc”);
Syste.out.println(p.getName());
}
使用BeanUutils給person( javabean)的對象p 的name屬性指派為xcc;
public void test2()throws IlegallAccessException,InvocationTargetException{
String name=”aaaa”;
String password=”123”;
String age=”34”;
String birthday=”1980-09-09”;
ConvertUtils.register(new DatelocalConverter(),Date.class);
Prerson p=new Person();
BeaUtils.setProperty(p.”name”,name);
BeaUtils.setProperty(p,”password”,”password”);
BeaUtils.setProperty(p,”age”,”age”);
BeaUtils.setProperty(p,”birthday”,”birthday”);
}
BeanUtils隻支援8種基本資料類型的自動轉換;如果是要轉換其它的需要轉換器;
如上面要把date 類型的的轉換成javabean中int 型的就注冊了轉換器;這裡的轉換器是jar包中帶的;
下面是時間轉換器的寫法:
ConvertUtils.register(new Converter()
{
public Object convert(Class type,Object value){
if(value==null){
return null;
}
If(!(value instansof String)){
throw new ConversionException(“隻支援String類型”);
}
String str=(String) value;
if(str.trim().equals(“”)){
return null;
}
SimpleDateFormat df=new SimpleDateFormat(“yyyy-MM-dd”);
try{
Return df.parse(str);
}catch(ParseException e){
e.printStackTrace();
}
}
},Date.class);
使用Map集合填充bean的屬性:
public void test4()throws IlegallAccessException,InvocationTargetException{
Map map=new HashMap();
map.put( “name”,”aaaa”);
map.put(“password’,”123”);
map.put(age,”34”);
map.put( birthday,”1980-09-09”);
ConvertUtils.register(new DatelocalConverter(),Date.class);
Prerson bean=new Person();
BeaUtils.populatey(bean,map);
}