`
lzh166
  • 浏览: 293996 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JavaBean 的简单内省(Intorspector)操作及BeanUtils工具类

 
阅读更多
1、对Javabean的简单的内省操作
问题 已知一个ReflectionPoint对象中有个私有变量的名字叫做'x'问采用反射如何得到它的值呢?
	/**
	* 实体内部类
	*/
	class ReflectionPoint{
		private int x;
		pirvate int y;
		public ReflectionPoint(int x,int y){
			this.x = x;
			this.y = y;
		}
		public void setX(int x){
			this.x = x;
		}
		public int getX(){
			return x;
		}
		public void setY(int y){
			this.y = y;
		}
		public int getY(){
			return y;
	}
	/**
	* main方法
	*/
	public static void main(String[] args) throws Exception{
		ReflectionPoint rp = new ReflectionPoint(3,5);
		String propertyName = "x";
		//利用反射,那我们会分析一步一步得到其属性的get方法: x -->X --->getX --->MethodGetX--操作
		//可想而知这样有点太麻烦了。我们并无法确定每个属性名称命名规范,所以导致我们获取方法时会有一定困难
		//不过JavaBean类中给我们提供了一些简便的类ropertyDescriptor
		//专门用于操作JavaBean对象的类PropertyDescriptor
		PropertyDescriptor pd = new PropertyDescriptor(propertyName, rp.getClass());//创建一个针对该JavaBean类和属性名的属性描述对象
		//getReadMethod()就相当于得到get方法,而getWriteMethod()就相当于是属性的set方法了。
		Method MethodGetX = pd.getReadMethod();
		//得到某个对象上的某个属性值
		Object retValue = MethodGetX.invoke(rp);
		//System.out.println(retValue);
		
		Method MethodSetY = pd.getWriteMethod();
		//设置某个对象上的某个属性值是7
		MethodSetY.invoke(rp, 7);
		System.out.println(rp.getX());
		
	}

2、对Javabean的复杂内省操作
当然也可使用Introspector类来完成这个功能,通过调用Introspector类的静态方法getBeanInfo得到一个BeanInfo类的对象,这个类可以把一个普通的类当成Javabean来看待 ,通过这个对象来得到所有属性的得到所有属性的描述的集合,然后采用遍历的方式逐一进行查找该属性,通过反射得到该方法,具体代码如下:
BeanInfo bi = Introspector.getBeanInfo(rp.getClass());
		PropertyDescriptor[] pds = bi.getPropertyDescriptors();
		Object retValue = null;
		
		for(PropertyDescriptor pd2 : pds) {
			if(pd2.getName().equals(propertyName)) {
				Method MethodGetX = pd2.getReadMethod();
				retValue = MethodGetX.invoke(rp);
				break;
			}
			
		}

3、使用BeanUtils工具包操作Javabean对象:
/**
		 * 利用BeanUtils工具类来调用属性
		 */
		System.out.println(BeanUtils.getProperty(stu, propertyName));
		System.out.println(BeanUtils.getProperty(stu, propertyName).getClass().getName());
		BeanUtils.setProperty(stu, "name", "前三");
		System.out.println(BeanUtils.getProperty(stu, propertyName));
		
		//设置一个对象的属性
		BeanUtils.setProperty(stu,"birthday.time","111");
		System.out.println(BeanUtils.getProperty(stu, "birthday.time"));
		System.out.println(retVal);
		
		/*//Jdk1.7新特性,设置map对象
		Map map = {name:"zhansan",age:12};
		BeanUtils.setProperty(map, name, "zhans");*/
		
		//另一种设置属性的方式
		
		PropertyUtils.setProperty(stu, propertyAge, 5);
		
		System.out.println(PropertyUtils.getProperty(stu, propertyAge).getClass().getName());
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics