黑马程序员_Java高新技术之内省综合案例

本文通过Eclipse演示如何自动生成ReflectPoint类的setter和getter方法,介绍使用PropertyDescriptor对象读取和设置JavaBean属性的方法,并提供代码示例。
---------------------- ASP.Net+Android+IO开发S.Net培训、期待与您交流! ----------------------
l 演示用 eclipse 自动生成 ReflectPoint 类的 setter getter 方法。
l 直接 new 一个 PropertyDescriptor 对象的方式来让大家了解 JavaBean API 的价值,先用一段代码读取 JavaBean 的属性,然后再用一段代码设置 JavaBean 的属性。
l 演示用 eclipse 将读取属性和设置属性的流水帐代码分别抽取成方法:
Ø 只要调用这个方法,并给这个方法传递了一个对象、属性名和设置值,它就能完成属性修改的功能。
Ø 得到 BeanInfo 最好采用“ obj.getClass ()” 方式,而不要采用“类名 .class” 方式,这样程序更通用。
l 采用遍历 BeanInfo 的所有属性方式来查找和设置某个 RefectPoint 对象的 x 属性。在程序中 把一个类当作 JavaBean 来看,就是调用 IntroSpector.getBeanInfo 方法,得到的 BeanInfo 对象封装了把这个类当作 JavaBean 看的结果信息。
public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		ReflectPoint pt1 = new ReflectPoint(3,5);
		Object retVal = getProperty(pt1);
		System.out.println(retVal);
		
		PropertyDescriptor pd2 = null;
		String propertyName = "y";
		Object value = 7;
		setProperty(pt1, propertyName, value);	
		
		//先通过调用普通java类的方法的方式获得结果,然后在这之前插入BeanUtil的get和set操作,见下面的代码。
		//System.out.println(pt1.getY());
		
		System.out.println(BeanUtils.getProperty(pt1, "y"));
		BeanUtils.setProperty(pt1, "y", "99");

		System.out.println(pt1.getY());
		PropertyUtils.setProperty(pt1, "y", 999);
		System.out.println(PropertyUtils.getProperty(pt1, "y").getClass().getName());	
	}

	private static Object getProperty(ReflectPoint pt1) {
		Object retVal = null;
		PropertyDescriptor pd = null;
		try {
			pd = new PropertyDescriptor("y",pt1.getClass());
			retVal = pd.getReadMethod().invoke(pt1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retVal;
	}

	private static void setProperty(Object pt1, String propertyName,
			Object value) {
		/*PropertyDescriptor pd2;
		try {
			pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
			pd2.getWriteMethod().invoke(pt1,value);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for(PropertyDescriptor pd :pds){
				if(pd.getName().equals(propertyName)){
					pd.getWriteMethod().invoke(pt1,value);
					break;
				}
			}
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值