首先导入 commons-logging.jar commons-beanutils-1.8.0.jar 这两个架包
用BeanUtils框架操作类的属性:
@Test
public void test1() throws Exception, InvocationTargetException{
Person p =new Person();
//使用反射技术,原理是拿到p.class,然后反射出name属性,再把属性值附到name属性中
BeanUtils.setProperty(p, "name","haha");
BeanUtils.getProperty(p,"name");
System.out.println(p.getName());
}
@Test
public void test2() throws Exception, InvocationTargetException{
Person p =new Person();
ConvertUtils.register(new Converter(){ //自己定义转换器可以使程序更加的健壮,当输入空日期时不至于报错
//BeanUtils.setProperty这个方法执行时会回调这个方法,进行日期的处理
public Object convert(Class arg0, Object value) {
// TODO Auto-generated method stub
if(value==null){ //当用户输入日期为空时,程序返回null;
return null;
}
String date=(String)value;
if(date.trim().equals("")){//当用户输入日期为空字符时,程序返回null;
return null;
}
SimpleDateFormat smf =new SimpleDateFormat("yyyy-MM-dd");//格式化日期
try {
return smf.parse(date);//转化
} catch (ParseException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
},Date.class); //自己定义一个转化器
BeanUtils.setProperty(p, "birthday","1999-01-01");
System.out.println(p.getBirthday());
}