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);
}