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;
}
}java.bean.PropertyDescriptor及其工具beanutils的学习
最新推荐文章于 2024-10-02 16:01:48 发布
本文介绍如何使用Java反射机制和commons-beanutils库操作JavaBean的属性。通过PropertyDescriptor类获取getter和setter方法,并演示了如何使用BeanUtils和PropertyUtils类设置和获取属性值。
8470

被折叠的 条评论
为什么被折叠?



