内省操作JavaBean

为了让程序员们更好的操作Java对象的属性,SUN公司开发了一套API,被业界内称为:内省;内省的出现有利于了对类对象属性的操作,减少了代码的数量。

内省访问JavaBean有两种方法:

       一、通过PropertyDescriptor来操作Bean对象

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

一、PropertyDescriptor类

javabean
public class Person {

	private String name;
	public String age;

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Person() {
		super();
	}

	public Person(String name, String age) {
		super();
		this.name = name;
		this.age = age;
	}
操作javabean
public static void main(String[] args) throws Exception {
		
		Person p = new Person("zhangsan","123");
		//name是Person类中属性
		String propertyName="name";
		//此时想要操作的是Person类中的name属性
		PropertyDescriptor pd = new PropertyDescriptor(propertyName, p.getClass());
		//根据名字得到属性的get方法
		Method merhodGetName = pd.getReadMethod();
		//执行Person类的get方法
		Object retVal= merhodGetName.invoke(p);

		System.out.println("retVal "+retVal);
		//得到Person类的set方法,我原本以为此时得到的应该是age的set方法,但是经验证此处操作的依然是name属性
		//Method methodSetAge = pd.getWriteMethod();
		
		PropertyDescriptor pd2 = new PropertyDescriptor("age",p.getClass());
		//此时pd2操作的就是age属性
		Method methodSetAge = pd2.getWriteMethod();
		
		//为对象p的age属性赋值100
		methodSetAge.invoke(p, "100");
		//得到age的get方法
		Method methodGetAge = pd2.getReadMethod();
		//执行age的get方法
		Object retVal2 = methodGetAge.invoke(p);
		
		System.out.println("retVal2 "+retVal2);
		
		System.out.println(p.getAge());
	}

输出
retVal zhangsan
retVal2 100
100

二、Introspector类

同样的javabean

操作javabean
public static void main(String[] args) throws Exception {

		Person p = new Person();

		// 通过Introspector来获取bean对象的beaninfo
		// BeanInfo bif = Introspector.getBeanInfo(Person.class);
		BeanInfo bif = Introspector.getBeanInfo(p.getClass());

		// 通过beaninfo来获得属性描述器(propertyDescriptor)
		PropertyDescriptor pds[] = bif.getPropertyDescriptors();

		// 通过属性描述器来获得对应的get/set方法
		for (PropertyDescriptor pd : pds) {

			// 获得并输出字段的名字
			System.out.println("pg.getname  " + pd.getName());
			// 获得并输出字段的类型
			System.out.println(pd.getPropertyType());

			if (pd.getName().equals("name")) {

				// 获得PropertyDescriptor对象的写方法
				Method md = pd.getWriteMethod();

				// 执行写方法
				md.invoke(p, "zhangsan");

			}
		}
		// 输出所赋值字段的值
		System.out.println(p.getName());

	}
输出
pg.getname  age
class java.lang.String
pg.getname  class
class java.lang.Class
pg.getname  name
class java.lang.String
zhangsan





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值