使用BeanUtils 并区分 PropertyUtils

在操作之前就先下Apache官网上下载相就的工具,这里我们要下载commons-beanutils 和commons-logging,我下载的版本是commons-beanutils-1.8.3和commons-logging-1.1.1,然后我选择的是commons-beanutils-1.8.3.jar和commons-logging-1.1.1.jar这两个jar包

 

演示用Eclipse如何加入jar包,先只是引入beanutils包,等程序运行出错后再引入logging包

在前面的内省例子的基础上,用 BeanUtils类先get原来设置好的属性,再将其set为一个新值。

get属性时返回的结果为该属性本来的类型,set属性时只接受该属性本来的类型。、

 

 

  BeanUtils.setProperty(pt1, "x","9"); //这里的9是String类型

  PropertyUtils.setProperty(pt1, "x", 9); //这里的是int类型

  //这两个类BeanUtils和PropertyUtils,前者能自动将int类型转化,后者不能 

 

public class IntroSpectorTest {
	public static void main(String[] args) throws Exception{
		ReflectPoint1 pt1 = new ReflectPoint1(3,5);
		String propertyName = "x";
		Object retval = getProperty(pt1, propertyName);
		System.out.println(retval);
		Object value = 7;
		setProperty(pt1, propertyName, value);
		
		System.out.println(BeanUtils.getProperty(pt1, "x")); //这里使用了Apache公司开发的BeanUtils工具包
		BeanUtils.setProperty(pt1, "x","9"); //这里的9是String类型
		PropertyUtils.setProperty(pt1, "x", 9); //这里的是int类型
			//这两个类BeanUtils和PropertyUtils,前者能自动将int类型转化,后者不能
		System.out.println(pt1.getX());
		BeanUtils.setProperty(pt1, "birthday.time", "111"); //一级一级调用实现
		System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));
//		Map map = {name:"xxx",age:18}; java 7新特性
//		BeanUtils.setProperty(map, "name", "zzz"); 可以实现map功能
	}

	private static void setProperty(Object pt1, String propertyName,
			Object value) throws IntrospectionException,
			IllegalAccessException, InvocationTargetException {
		PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, pt1.getClass()); //propertyName为字段名
		//javaBean的操作方式
		Method methodSetx = pd2.getWriteMethod(); //调用该字段的setxxx方法
		methodSetx.invoke(pt1, value);
	}

	private static Object getProperty(Object pt1, String propertyName)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
		/*
		PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());
		Method methodGetX = pd.getReadMethod();//调用该字段的getxxxx方法
		Object retval = methodGetX.invoke(pt1);
		return retval;
		*/
		BeanInfo beaninfo = Introspector.getBeanInfo(pt1.getClass());
		PropertyDescriptor[] pds = beaninfo.getPropertyDescriptors();
		Object retVal = null;
		for (PropertyDescriptor pd: pds) {
			if (pd.getName().equals(propertyName)) {
				Method methodGetX = pd.getReadMethod();
				retVal = methodGetX.invoke(pt1);
				break;
			}
		}
		return retVal;
	}
}

 

posted @ 2013-05-20 00:32  乖乖爽  阅读(1270)  评论(0编辑  收藏  举报