您的位置:首页 > 编程语言 > Java开发

java.bean.PropertyDescriptor及其工具beanutils的学习

2013-12-27 00:15 447 查看
public class ItroSpectorTest extends TestCase {

//利用PropertyDescription类的getReadMethod获取javabean的get方法
public void testPropertyDescriptor_Get() throws Exception{
//利用java.beans.PropertyDescriptor获取读属性和设置属性的方法
Student stu = createStu();
//新建一个PropertyDescriptor对象,传入类名和属性名
PropertyDescriptor pd=new PropertyDescriptor("id", stu.getClass());
Method methodGetId=pd.getReadMethod();
Object retVal=methodGetId.invoke(stu);
System.out.println("测试PropertyDescription类的getReadMethod方法"+retVal);
}
//利用PropertyDescription类的getWriteMethod获取javabean的set方法
public void testPropertyDescriptor_Set() throws Exception{
Student stu=createStu();
PropertyDescriptor pd=new PropertyDescriptor("id", stu.getClass());
Method methodSetId=pd.getWriteMethod();
methodSetId.invoke(stu, 2);
System.out.println(stu.getId());
}
//利用commons-beanutils的类BeanUtils设置javabean对象的属性
public void testBeanUtilsSet() throws Exception{
Student stu=createStu();
//值可以为字符串,内部进行类型转换
BeanUtils.setProperty(stu, "id", "2");
System.out.println(stu.getId());
}
//利用commons-beanutils的类BeanUtils获取javabean对象的属性
public void testBeanUtilsGet() throws Exception{
Student stu=createStu();
String retVal=BeanUtils.getProperty(stu, "id");
System.out.println(retVal);
}
//利用commons-beanutils的类BeanUtils级联获取javabean对象的属性,比如获取Date类型的time值
public void testBeanUtilsGet2() throws Exception{
Student stu=createStu();
String retVal=BeanUtils.getProperty(stu, "birthday.time");

System.out.println(retVal);
}
//利用commons-beanutils的类PropertyUtils设置javabean对象的属性
public void testPropertyUtilsSet() throws Exception{
Student stu=createStu();
//PropertyUtils.setProperty(stu, "id", "2");//java.lang.IllegalArgumentException: argument type mismatch
PropertyUtils.setProperty(stu, "id", 2);
System.out.println(stu.getId());
}
//利用commons-beanutils的类PropertyUtils获取javabean对象的属性
public void testPropertyUtilsGet() throws Exception{
Student stu=createStu();
PropertyUtils.getProperty(stu, "id");
}
//准备测试数据
private Student createStu() {
//新建一个Student对象,作为测试对象
Date birth=new Date();
Calendar cal=new GregorianCalendar(1991, 3, 21);
birth=cal.getTime();
Student stu=new Student(1,"yyf",birth,22);
return stu;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: