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是一种特殊的类,主要用于传 ...
随机推荐
- 2017-12-01 中英文代码对比之ZLOGO 4 & LOGO
基于前文中文编程语言之Z语言初尝试: ZLOGO 4的一些评论, 此文尝试作一个非常简单的代码对比, 使讨论更加有实例根据. 下图是节选自前文最后的示例代码, 由于选取的对照LOGO版本 (alanc ...
- 后台返回xml格式转json
之前后台做了一个xml格式的数据返回给前端,这个可愁坏了我,不过现在还是解决了,虽然方法有点笨,但没有找到其他的方法,先将就着用吧. 后台返回的是这样的: 那么我们就要这样处理:commonMetho ...
- Django之form总结
复习Django项目结构: 主要的文件:manage.py,url.py,views.py,settings.py,models.py manage.py:项目管理文件,一般不做修改. url.py: ...
- [20180403]访问dba_autotask_task无输出问题.txt
[20180403]访问dba_autotask_task无输出问题.txt --//链接http://www.itpub.net/thread-1911421-1-1.html的讨论,还没注意原先的 ...
- centos6.9NAT网络模式
1.对虚拟机进行设置,点击该虚拟机的设置在网络适配器下将网络连接设置为NAT模式. 2.对虚拟机进行设置,点击虚拟机左上方的编辑-->虚拟网络编辑器,将WMnet信息设置为NAT模式,其它的无需 ...
- 8.1Python面向对象编程(一)
目录 目录 前言 (一)基本概念 ==1.面向过程与面向对象== ==2.类与对象== (二)类属性的相关操作 ==1.定义一个经典类== ==2.对象属性的操作== ==3.类属性的操作== ==4 ...
- 6.3Pytyhon文件的操作(三)
目录 目录 前言 (一)文件的创建 (二)文件的删除 (三)文件的重命名 (四)文件的查看 (五)文件的复制 ==1.小文件的复制== ==2.大文件的复制== (六)文件的实战案例 ==1.文件的分 ...
- Linux 小知识翻译 - 「架构」(arch)
这次,聊聊「架构」这个术语. 在PC相关的文档中,是不是经常看到「x86架构」这个短句.但是对于这句话,是不是总感到有种似懂非懂的感觉. 架构的英语是「architecture」.这里面有「建筑」,「 ...
- Appium1.9.1 之 Desired Capabilities 释疑
服务关键字 Desired Capabilities在启动session的时候是必须提供的. Desired Capabilities本质上是以key value字典的方式存放,客户端将这些键值对发给 ...
- 深入探究JFreeChart
1 简介 JFreeChart 是 SourceForge.net 上的一个开源项目,它的源码和 API 都可以免费获得. JFreeChart 的功能非常强大,可以实现饼图 ( 二维和三维 ) , ...