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

来源:互联网 发布:淘宝韩都衣舍女装 编辑:程序博客网 时间:2024/06/09 17:21
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 mismatchPropertyUtils.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;}}

0 0