Introspector内省机制学习

1、内省机制是用来操作javabean。

2、java属性是指 get或者set方法,跟变量无关。

3、内省的基本操作

内省一个类,获取出Bean的方法。


BeanInfo bean = Introspector.getBeanInfo(Person.class);
获取所有的属性描述器



PropertyDescriptor[] descriptors = bean.getPropertyDescriptors();//获取所有属性的属性描述器
获取属性的名字



descriptor.getName();


整段代码


public void test7() throws IntrospectionException {
        BeanInfo bean = Introspector.getBeanInfo(Person.class);
        PropertyDescriptor[] descriptors = bean.getPropertyDescriptors();//获取所有属性的属性描述器
        for (PropertyDescriptor  descriptor:descriptors){
              print(descriptor.getName());
        }
    }

生成的结果会包含Person里的所有属性和一个class属性,而class属性是Object里的,所以当我们需要一个完整Person而不包含继承来的属性的时候需要排除掉。

BeanInfo bean = Introspector.getBeanInfo(Person.class,Object.class);


4、利用内省机制来使用属性

实例化bean对象并且使用属性描述器来获取bean中的属性,以name为例子,name必须有符合javabean规范get set方法

Person p  = new Person();
PropertyDescriptor descriptor = new PropertyDescriptor("name",Person.class);
获取set方法并且设值

Method writeMethod = descriptor.getWriteMethod();
writeMethod.invoke(p,"中国");
获取get方法获取值

Method readMethod = descriptor.getReadMethod();
Object invoke = readMethod.invoke(p, null);
print((String) invoke);
获取某个变量的类型

Class<?> propertyType = descriptor.getPropertyType();
print(propertyType.toString());





转载于:https://my.oschina.net/u/167671/blog/171697

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值