java api内省的流程

流程:

第一,得到所有属性描述器
得到bean--》
得到bean的所有属性信息info(Introspector.getBeanInfo(bean.class))
--》
得到所有属性的描述器()info.getPropertyDescriptiors pds[]
-->遍历pds,得到每个属性的描述器
--》pd.getName,可以得到所有的属性名
--》通过属性名,获得想要的属性,
--》得到属性的get,set方法(pd.getReadMethod,pd.getWriteMethod)
--》使用,method.invoke(bean,"属性值");可以调用方法
第二,得到bean指定的属性的描述器
可以通过PropertyDescriptor的构造方法,得到指定属性名的属性
new PropertyDescriptor(propertyName,bean.class)


1.为什么要学内省?

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

2.内省访问JavaBean属性的两种方式:

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

3.Sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils
Beanutils工具包的常用类:
BeanUtils
PropertyUtils
ConvertUtils.regsiter(Converter convert, Class clazz)
自定义转换器

4.commons-beanutils.jar log4j.jar

5.以下为java api中的内省方法

Student bean = new Student();

//得到bean的所有属性
BeanInfo info = Introspector.getBeanInfo(Student.class);

//得到bean的所有属性描述器
PropertyDescriptor pds[] = info.getPropertyDescriptors();

for(PropertyDescriptor pd : pds){ //name
String propertyName = pd.getName();
if(propertyName.equals("name")){
Method m = pd.getWriteMethod(); //setName(String name)
m.invoke(bean, "flx");
}
}
System.out.println(bean.getName());
}

//操作bean的指定属性: age
@Test
public void test2() throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{

Student bean = new Student();
PropertyDescriptor pd = new PropertyDescriptor("age",bean.getClass());
Method method = pd.getWriteMethod(); //setAge(int age)
method.invoke(bean, 12);

//通过内省获取bean的age属性
method = pd.getReadMethod(); // getAge()
int age = (Integer) method.invoke(bean, null);
System.out.println(age);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值