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

本文介绍如何使用Java反射机制和commons-beanutils库操作JavaBean的属性。通过PropertyDescriptor类获取getter和setter方法,并演示了如何使用BeanUtils和PropertyUtils类设置和获取属性值。
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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值