博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Introspector内省机制学习
阅读量:6989 次
发布时间:2019-06-27

本文共 1272 字,大约阅读时间需要 4 分钟。

hot3.png

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

你可能感兴趣的文章
Ruby实现二分法查找
查看>>
知之者不如好之者,好之者不如乐之者
查看>>
我的友情链接
查看>>
Office365 SKU-1
查看>>
通过JDBC向数据库中存储&读取Blob数据
查看>>
2019年我国云计算行业存在的问题和发展趋势
查看>>
内置模块(二)
查看>>
C编程技巧
查看>>
week5
查看>>
Unity3D常用网络框架与实战解析 学习
查看>>
继承(原型链继承)
查看>>
如何利用 Visual Studio 自定义项目或工程模板(转载)
查看>>
java.lang.Object底层代码分析-jdk1.8
查看>>
获取函数所在模块的方法
查看>>
QtTableView
查看>>
Android应用开发基础--Adapter
查看>>
条件随机场
查看>>
别人要访问我的电脑上部署的tomcat,必须关闭防火墙吗?
查看>>
作业六
查看>>
c++ 二叉树打印节点路径
查看>>