Java中的内省

         内省(Introspector)是Java语言对 Bean类属性、事件的一种缺省处理方法。例如类A中有属性name,那我们可以通过getName,setName来得到其值或者设置新的值。通过 getName/setName来访问name属性,这就是默认的规则。

有两种方法可以这样操作JavaBean:

       一、通过Introspector类获得描述目标bean的 BeanInfo对象,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取JavaBean里属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。

       二、通过PropertyDescriptor直接操作Bean对象,然后再用反射来操作

       首先是要操作的javabean:Person.java

package cn.wang.introtationtest;

public class Person {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

     方法一:

package cn.wang.introtationtest;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class IntrotationTest1 {
	
	public static void main(String[] args) throws Exception {
		
		Person p = new Person();
		
		//1、通过Introspactor的getBeanInfo方法获得描述目标 bean的 BeanInfo对象		
		BeanInfo beanInfo = Introspector.getBeanInfo(p.getClass());
		
		//2、通过BeanInfo的getPropertyDescriptors()方法获得属性的描述器 ,返回类型是PropertyDescriptors的数组		
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
		
		//3、对pds进行遍历,得到get和set方法
		for(PropertyDescriptor pd:pds){
			
			System.out.println(pd.getName());
			
			//4、判断是否是name属性		
			if(pd.getName().equals("name")){
				
				//5、通过PropertyDescriptors的getWriteMethod方法获得写属性的方法,返回一个Method对象	
				Method writeMethod = pd.getWriteMethod();
				
				//6、通过Method类的invoke方法对属性进行赋值
				writeMethod.invoke(p, "wang");
				
				//7、读取方法
				Method readMethod = pd.getReadMethod();
				
				//由于读方法无需对属性进行赋值,所以invoke方法只需设置操作对象即可
				Object retVal = readMethod.invoke(p);
				
				System.out.println(retVal);
			}
			
		}
	
	}

}
     方法二:

package cn.wang.introtationtest;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class IntrotationTest2 {

	public static void main(String[] args) throws Exception {
		
		Person p = new Person();
		
		//1、通过PropertyDescriptor的构造方法获得属性的描述器
		PropertyDescriptor pd = new PropertyDescriptor("name",p.getClass());
		
		//2、通过PropertyDescriptor的对象获得写方法
		Method writeMethod = pd.getWriteMethod();
		//3、赋值
		writeMethod.invoke(p, "wang");
		
		//4、获得读方法
		Method readMethod = pd.getReadMethod();
		
		//5、执行读方法
		readMethod.invoke(p);
		
		System.out.println(p.getName());

	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值