Introspector(内省)

开发框架时,经常需要使用java对象的属性来封装程序的数据,每次都使用反射技术完成此类操作过于麻烦,所以sun公司开发了一套API,专门用于操作java对象的属性。


内省主要解决的问题:把对象的属性数据封装到对象中。


1.通过PropertyDescriptor类操作Bean的属性

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

package com.cn.introspector;
import static org.junit.Assert.*;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Test;
/**
* Author:Liu Zhiyong(QQ:1012421396)
* Version:Version_1
* Date:2016年8月29日18:43:08
* Desc:
内省:
内省主要解决的问题:把对象的属性数据封装到对象中。
*/
public class Demo2 {
		
	@Test
	public void testGetAllProperty() throws Exception {
		//Introspector内省
		BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
		//通过beanInfo获取一个类中的所有属性描述器
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for(PropertyDescriptor p : propertyDescriptors){
			System.out.println(p.getReadMethod());//get方法
		}
	}
	
	@Test
	public void testProperty() throws Exception{
		Person p = new Person();
		
		//属性描述器
		PropertyDescriptor descriptor = new PropertyDescriptor("id", Person.class);
		//获取属性对应的get或者set方法获取或者设置属性
		Method writeMethod = descriptor.getWriteMethod(); //获取属性的set方法
		//执行该方法,设置属性值
		writeMethod.invoke(p, 120);
		
		Method readMethod = descriptor.getReadMethod();
		//执行该方法,获取属性值
		System.out.println(readMethod.invoke(p, null));
		System.out.println(p);
	}
}
package com.cn.introspector;
public class Person {
	int id;
	String name;
	public Person(int id, String name) {
		this.id = id;
		this.name = name;
	}
	
	public Person() {
	}
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "编号:" + this.id + "\t姓名:" + this.name;
	}
}


存在的问题: sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值