Java:内省(Introspector)
内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。
JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信 息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。
例如UserInfo
public class UserInfo {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
publicint getAge() {
return age;
}
publicvoid setAge(int age) {
this.age = age;
}
}
在UserInfo中有属性name,我们可以通过getName,setName来访问其值或者设置其值.通过getName/setName来访问其属性name,这就是默认规则,java jdk中提供一套api用来访问某个属性的getter(),setter()方法即为内省。
JDK内省类库:
PropertyDescriptor类:
表示JavaBean类通过存储器导出一个属性。
主要方法:
1. getPropertyType(),获得属性的Class对象;
2. getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
3. hashCode(),获取对象的哈希值;
4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method; public class BeanInfoUtil { public static void main(String[] args) {
UserInfo user = new UserInfo();
try {
setProperty(user, "name");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(user.getName());
System.out.println(getProperty(UserInfo.class, "name"));
} public static void setProperty(Object bean, String propertyName) throws Exception {
PropertyDescriptor pd = new PropertyDescriptor(propertyName, bean.getClass());
Method methodSetProperty = pd.getWriteMethod();
methodSetProperty.invoke(bean, "123");
} public static String getProperty(Class<?> bean, String propertyName) {
try {
//通过反射实例化对象
Object be = bean.newInstance();
//创建PropertyDescriptor对象
PropertyDescriptor pd = new PropertyDescriptor(propertyName, be.getClass());
//调用getWriteMethod方法来为对象属性设置值
pd.getWriteMethod().invoke(be, "123");
//调用getReadMethod方法来获取对象的属性值
return (String) pd.getReadMethod().invoke(be, new Object[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
} class UserInfo {
private String name;
private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}
Introspector类:
将JavaBean中的属性封装起来进行操作。在程序把一个类当做JavaBean来看,就是调用Introspector.getBeanInfo()方法,得到的BeanInfo对象封装了把这个类当做JavaBean看的结果信息,即属性的信息。
getPropertyDescriptors(),获得属性的描述,可以采用遍历BeanInfo的方法,来查找、设置类的属性。具体代码如下:
public static void setPropertyIntrospector(Class<?> bean, String propertyName) {
try {
//第一个参数要分析的bean类,
//第二个参数是从第一个参数开始到某个父类结束(当bean存在多个父类的时候可以通过该方法来限定)
BeanInfo beanInfo = Introspector.getBeanInfo(bean, Object.class);
//获取整个bean的属性描述
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
if(pds != null && pds.length > 0) {
for(PropertyDescriptor pd : pds) {
if(pd.getName().equals(propertyName)) {
Object obj = bean.newInstance();
pd.getWriteMethod().invoke(obj, "张三");
System.out.println(pd.getReadMethod().invoke(obj, new Object[0]));
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
======================使用内省机制完成javaBean和Map之间的相互转换====================
public static Map<String, Object> beanToMap(Object bean) {
if(bean == null) return null;
try {
Map map = newHashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
if(pds != null && pds.length > 0) {
for(PropertyDescriptor pd : pds) {
String key = pd.getName();
//过滤掉class属性
if(!key.equals("class")) {
Object value = pd.getReadMethod().invoke(bean, new Object[]{});
//此处如果明确知道该类中含有某个对象可以这种处理
if(value instanceof Person) {
//递归调用
Map m = beanToMap(value);
map.put(key, m);
} else {
map.put(key, value);
}
}
}
}
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object mapToBean(Class<?> beanClass, Map map) {
if(map == null) return null;
try {
//内部实例化对象
Object bean = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
if(pds != null && pds.length > 0) {
for(PropertyDescriptor pd : pds) {
String key = pd.getName();
Object value = map.get(key);
if(value instanceof Map) {
//递归调用,嵌套map的转换,map中存放map,map中的map表示一个对象
Object obj = mapToBean(Person.class, (Map)value);
pd.getWriteMethod().invoke(bean, obj);
} else {
pd.getWriteMethod().invoke(bean, value);
}
}
}
return bean;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Java:内省(Introspector)的更多相关文章
- Java 内省(Introspector)深入理解
Java 内省(Introspector)深入理解 一些概念: 内省(Introspector) 是Java 语言对 JavaBean 类属性.事件的一种缺省处理方法. JavaBean是一种特殊的类 ...
- Java 内省(Introspector)和 BeanUtils
人生若只如初见,何事秋风悲画扇. 概述 内省(Introspector) 是Java 语言对 JavaBean 类属性.事件的一种缺省处理方法. JavaBean是一种特殊的类,主要用于传递数据信息, ...
- JAVA内省(Introspector)
什么是Java内省:内省是Java语言对Bean类属性.事件的一种缺省处理方法. Java内省的作用:一般在开发框架时,当需要操作一个JavaBean时,如果一直用反射来操作,显得很麻烦:所以sun公 ...
- 聊聊Java内省Introspector
前提 这篇文章主要分析一下Introspector(内省,应该读xing第三声,没有找到很好的翻译,下文暂且这样称呼)的用法.Introspector是一个专门处理JavaBean的工具类,用来获取J ...
- Java 内省 Introspector
操纵类的属性,有两种方法 反射 内省 面向对象的编程中,对于用户提交过来的数据,要封装成一个javaBean,也就是对象 其中Bean的属性不是由字段来决定的,而是由get和Set方法来决定的 pub ...
- java内省Introspector
大纲: JavaBean 规范 内省 一.JavaBean 规范 JavaBean —般需遵循以下规范. 实现 java.io.Serializable 接口. javaBean属性是具有getter ...
- 【小家Spring】Spring IoC是如何使用BeanWrapper和Java内省结合起来给Bean属性赋值的
#### 每篇一句 > 具备了技术深度,遇到问题可以快速定位并从根本上解决.有了技术深度之后,学习其它技术可以更快,再深入其它技术也就不会害怕 #### 相关阅读 [[小家Spring]聊聊Sp ...
- 【小家Spring】聊聊Spring中的数据绑定 --- BeanWrapper以及内省Introspector和PropertyDescriptor
#### 每篇一句 > 千古以来要饭的没有要早饭的,知道为什么吗? #### 相关阅读 [[小家Spring]聊聊Spring中的数据转换:Converter.ConversionService ...
- 深入理解Java:内省(Introspector)
深入理解Java:内省(Introspector) 内省(Introspector) 是Java 语言对 JavaBean 类属性.事件的一种缺省处理方法. JavaBean是一种特殊的类,主要用于传 ...
随机推荐
- deepin使用笔记-解决蓝牙设备开机自动开启的问题
我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 1.安装蓝牙驱动管理 #apt-get install blueman 2.打开蓝牙驱动管理,关闭设备 3.关闭蓝牙开机启动服务 ...
- blfs(systemv版本)学习笔记-前几章节的脚本配置
我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 记录blfs书籍前几个章节的配置内容. bash shell启动文件章节 1.切换root用户 su 2.创建/etc/prof ...
- FIFO、LRU、LFU的含义和原理
含义: FIFO:First In First Out,先进先出LRU:Least Recently Used,最近最少使用 LFU:Least Frequently Used,最不经常使用 以上三者 ...
- BZOJ2564: 集合的面积(闵可夫斯基和 凸包)
题意 题目链接 Sol 这个东西的学名应该叫"闵可夫斯基和".就是合并两个凸包 首先我们先分别求出给出的两个多边形的凸包.合并的时候直接拿个双指针扫一下,每次选最凸的点就行了. 复 ...
- [笔记] imooc《JavaScript深入浅出》对象与函数
懒得做草稿了,习惯md也懒得扔印象笔记 主要是之前没去接触这一部分,就随手记下来了 创建对象的方法 对象字面量 new构造器/原型链 Object.create() 属性操作 属性读写(以及读写异常. ...
- 【读书笔记】iOS-设置应用的硬件需求
如果你的应用需要一些特定的硬件设备才能运行,你可以在应用的Info.plist文件中添加应用运行所需的硬件列表.如果设备上没有这些硬件的话,你的应用将不会启动. 如图,找到Info.Plist---& ...
- python之管道, 事件, 信号量, 进程池
管道:双向通信 2个进程之间相互通信 from multiprocessing import Process, Pipe def f1(conn): from_zjc_msg = conn.recv( ...
- SuperMap iServer 扩展/JAVA API 系列博客整理
转载:http://blog.csdn.net/supermapsupport/article/details/70158940 SuperMap iServer为广大用户提供了整套 SDK,应用开发 ...
- python自动发送测试报告(五)
python实现自动发送邮件具体步骤参考笔者的另一篇博文,python实现邮件的发送 本次只展示发送附件的代码,MIMEApplication支持常用格式文档(.jpg..mp3.zip等)当做附件上 ...
- 基于 node 搭建博客系统(一)
系统分为两端,分别实现. 管理员端: 功能 :个人信息,设置,发布随笔,随笔列表,删除随笔,查找,文章 等. 技术点:Boostrap + AdminLTE; 基于nodejs 实现的express ...