深入理解Java:内省(Introspector)
内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。
JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。
例如类UserInfo :
package com.peidasoft.Introspector;public class UserInfo {private long userId;private String userName;private int age;private String emailAddress;public long getUserId() {return userId;}public void setUserId(long userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getEmailAddress() {return emailAddress;}public void setEmailAddress(String emailAddress) {this.emailAddress = emailAddress;}}
在类UserInfo中有属性 userName, 那我们可以通过 getUserName,setUserName来得到其值或者设置新的值。通过 getUserName/setUserName来访问 userName属性,这就是默认的规则。 Java JDK中提供了一套 API 用来访问某个属性的 getter/setter 方法,这就是内省。
JDK内省类库:
PropertyDescriptor类:
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
1. getPropertyType(),获得属性的Class对象;
2. getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
3. hashCode(),获取对象的哈希值;
4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
实例代码如下:
package com.peidasoft.Introspector;import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method;public class BeanInfoUtil { public static void setProperty(UserInfo userInfo,String userName)throws Exception{PropertyDescriptor propDesc=new PropertyDescriptor(userName,UserInfo.class);Method methodSetUserName=propDesc.getWriteMethod();methodSetUserName.invoke(userInfo, "wong");System.out.println("set userName:"+userInfo.getUserName());} public static void getProperty(UserInfo userInfo,String userName)throws Exception{PropertyDescriptor proDescriptor =new PropertyDescriptor(userName,UserInfo.class);Method methodGetUserName=proDescriptor.getReadMethod();Object objUserName=methodGetUserName.invoke(userInfo);System.out.println("get userName:"+objUserName.toString());} }
Introspector类:
将JavaBean中的属性封装起来进行操作。在程序把一个类当做JavaBean来看,就是调用Introspector.getBeanInfo()方法,得到的BeanInfo对象封装了把这个类当做JavaBean看的结果信息,即属性的信息。
getPropertyDescriptors(),获得属性的描述,可以采用遍历BeanInfo的方法,来查找、设置类的属性。具体代码如下:
package com.peidasoft.Introspector;import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method;public class BeanInfoUtil {public static void setPropertyByIntrospector(UserInfo userInfo,String userName)throws Exception{BeanInfo beanInfo=Introspector.getBeanInfo(UserInfo.class);PropertyDescriptor[] proDescrtptors=beanInfo.getPropertyDescriptors();if(proDescrtptors!=null&&proDescrtptors.length>0){for(PropertyDescriptor propDesc:proDescrtptors){if(propDesc.getName().equals(userName)){Method methodSetUserName=propDesc.getWriteMethod();methodSetUserName.invoke(userInfo, "alan");System.out.println("set userName:"+userInfo.getUserName());break;}}}}public static void getPropertyByIntrospector(UserInfo userInfo,String userName)throws Exception{BeanInfo beanInfo=Introspector.getBeanInfo(UserInfo.class);PropertyDescriptor[] proDescrtptors=beanInfo.getPropertyDescriptors();if(proDescrtptors!=null&&proDescrtptors.length>0){for(PropertyDescriptor propDesc:proDescrtptors){if(propDesc.getName().equals(userName)){Method methodGetUserName=propDesc.getReadMethod();Object objUserName=methodGetUserName.invoke(userInfo);System.out.println("get userName:"+objUserName.toString());break;}}}}}
通过这两个类的比较可以看出,都是需要获得PropertyDescriptor,只是方式不一样:前者通过创建对象直接获得,后者需要遍历,所以使用PropertyDescriptor类更加方便。
使用实例:
package com.peidasoft.Introspector;public class BeanInfoTest {/*** @param args*/public static void main(String[] args) {UserInfo userInfo=new UserInfo();userInfo.setUserName("peida");try {BeanInfoUtil.getProperty(userInfo, "userName");BeanInfoUtil.setProperty(userInfo, "userName");BeanInfoUtil.getProperty(userInfo, "userName");BeanInfoUtil.setPropertyByIntrospector(userInfo, "userName"); BeanInfoUtil.getPropertyByIntrospector(userInfo, "userName");BeanInfoUtil.setProperty(userInfo, "age");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
输出:
get userName:peida set userName:wong get userName:wong set userName:alan get userName:alan java.lang.IllegalArgumentException: argument type mismatchat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)at java.lang.reflect.Method.invoke(Method.java:597)at com.peidasoft.Introspector.BeanInfoUtil.setProperty(BeanInfoUtil.java:14)at com.peidasoft.Introspector.BeanInfoTest.main(BeanInfoTest.java:22)
说明:BeanInfoUtil.setProperty(userInfo, "age");报错是应为age属性是int数据类型,而setProperty方法里面默认给age属性赋的值是String类型。所以会爆出argument type mismatch参数类型不匹配的错误信息。
BeanUtils工具包:
由上述可看出,内省操作非常的繁琐,所以所以Apache开发了一套简单、易用的API来操作Bean的属性——BeanUtils工具包。
BeanUtils工具包:下载:http://commons.apache.org/beanutils/ 注意:应用的时候还需要一个logging包 http://commons.apache.org/logging/
使用BeanUtils工具包完成上面的测试代码:
package com.peidasoft.Beanutil;import java.lang.reflect.InvocationTargetException;import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils;import com.peidasoft.Introspector.UserInfo;public class BeanUtilTest {public static void main(String[] args) {UserInfo userInfo=new UserInfo();try {BeanUtils.setProperty(userInfo, "userName", "peida");System.out.println("set userName:"+userInfo.getUserName());System.out.println("get userName:"+BeanUtils.getProperty(userInfo, "userName"));BeanUtils.setProperty(userInfo, "age", 18);System.out.println("set age:"+userInfo.getAge());System.out.println("get age:"+BeanUtils.getProperty(userInfo, "age"));System.out.println("get userName type:"+BeanUtils.getProperty(userInfo, "userName").getClass().getName());System.out.println("get age type:"+BeanUtils.getProperty(userInfo, "age").getClass().getName());PropertyUtils.setProperty(userInfo, "age", 8);System.out.println(PropertyUtils.getProperty(userInfo, "age"));System.out.println(PropertyUtils.getProperty(userInfo, "age").getClass().getName());PropertyUtils.setProperty(userInfo, "age", "8"); } catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}catch (NoSuchMethodException e) {e.printStackTrace();}} }
运行结果:
set userName:peida get userName:peida set age:18 get age:18 get userName type:java.lang.String get age type:java.lang.String 8 java.lang.Integer Exception in thread "main" java.lang.IllegalArgumentException: Cannot invoke com.peidasoft.Introspector.UserInfo.setAge on bean class 'class com.peidasoft.Introspector.UserInfo' - argument type mismatch - had objects of type "java.lang.String" but expected signature "int"at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2235)at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:2151)at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1957)at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:2064)at org.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:858)at com.peidasoft.orm.Beanutil.BeanUtilTest.main(BeanUtilTest.java:38) Caused by: java.lang.IllegalArgumentException: argument type mismatchat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)at java.lang.reflect.Method.invoke(Method.java:597)at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2170)... 5 more
说明:
1.获得属性的值,例如,BeanUtils.getProperty(userInfo,"userName"),返回字符串
2.设置属性的值,例如,BeanUtils.setProperty(userInfo,"age",8),参数是字符串或基本类型自动包装。设置属性的值是字符串,获得的值也是字符串,不是基本类型。 3.BeanUtils的特点:
1). 对基本数据类型的属性的操作:在WEB开发、使用中,录入和显示时,值会被转换成字符串,但底层运算用的是基本类型,这些类型转到动作由BeanUtils自动完成。
2). 对引用数据类型的属性的操作:首先在类中必须有对象,不能是null,例如,private Date birthday=new Date();。操作的是对象的属性而不是整个对象,例如,BeanUtils.setProperty(userInfo,"birthday.time",111111);
package com.peidasoft.Introspector; import java.util.Date;public class UserInfo {private Date birthday = new Date();public void setBirthday(Date birthday) {this.birthday = birthday;}public Date getBirthday() {return birthday;} }
package com.peidasoft.Beanutil;import java.lang.reflect.InvocationTargetException; import org.apache.commons.beanutils.BeanUtils; import com.peidasoft.Introspector.UserInfo;public class BeanUtilTest {public static void main(String[] args) {UserInfo userInfo=new UserInfo();try {BeanUtils.setProperty(userInfo, "birthday.time","111111"); Object obj = BeanUtils.getProperty(userInfo, "birthday.time"); System.out.println(obj); } catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}catch (NoSuchMethodException e) {e.printStackTrace();}} }
3.PropertyUtils类和BeanUtils不同在于,运行getProperty、setProperty操作时,没有类型转换,使用属性的原有类型或者包装类。由于age属性的数据类型是int,所以方法PropertyUtils.setProperty(userInfo, "age", "8")会爆出数据类型不匹配,无法将值赋给属性。
参考资料:
1.http://www.cnblogs.com/avenwu/archive/2012/02/28/2372586.html
2.http://blog.csdn.net/zhuruoyun/article/details/8219333
转载于:https://www.cnblogs.com/fengbo-itcast/p/6385654.html
深入理解Java:内省(Introspector)相关推荐
- 【java】Java内省Introspector
1.概述 直通车:https://www.cnblogs.com/throwable/p/13473525.html
- java 中的内省 introspector
概述 经常需要使用java对象的属性来封装程序的数据,每次都使用反射技术完成此类操作过于麻烦,所以sun公司开发了一套API,专门用于操作java对象的属性. 内省(IntroSpector)是Jav ...
- java内省_java内省机制
一.内省是什么.实现方式: 内省(Introspector)是Java语言对Bean类属性.事件的一种缺省处理方法. 例如类A中有属性name,那我们可以通过getName,setName来得到其值或 ...
- java内省的意思_java内省和反射的区别
展开全部 经过多方面的资料搜集整理,写下了这篇文章,本文主要讲解java的反射和内e68a843231313335323631343130323136353331333363366237省机制,希望对 ...
- java内省的意思,java内省机制 + 内省是什么 + 内省实现方式 + 和反射的区别
见:https://zhidao.baidu.com/question/434288330.html.http://blog.csdn.net/u014394715/article/details/5 ...
- java内省和反射机制_Java内省和反射机制三步曲之 - 内省
经过多方面的资料搜集整理,写下了这篇文章,本文主要讲解java的反射和内省机制,希望对大家有点帮助,也希望大家提出不同的看法! 1).内省(Introspector)是 Java 语言对 Bean 类 ...
- java内省有什么作用_Java内省
1. 什么是内省? 内省(Introspector)是Java语言对JavaBean类属性.事件的处理方法. 例如类User中有属性name,那么必定有getName,setName方法,我们可以通 ...
- java内省操作类的属性
java内省操作类的属性 1.取得指定类的属性的方法 2.操作指定类的属性的方法 3.得到指定类的属性数据类型的方法 package com.ma.introspector;import java.b ...
- java 内省 反射_Java的反射和内省
1.反射 反射是指在运行过程中,可以获取任意类的属性和方法信息; 对于任意对象,都可以获取调用其任意方法; 这种动态获取类信息和动态调用对象方法的方式称为Java语言的反射机制; public cla ...
最新文章
- Vivado 随笔(2) 综合属性之use_dsp48?
- linux 更改文件权限(子文件夹)
- HTML<div>标签、<img>标签
- 关于“服务器提交了协议冲突. Section=ResponseStatusLine问题请
- C开源hash代码uthash的用法总结(2)
- 一叶知秋:“安全“的野指针、 static函数、成员函数、this 指针、gcc编译器、name mangling
- 设计模式 之 《工厂方法模式》
- 层叠性(HTML、CSS)
- opencv配置环境吐血经验
- 手机app的性能测试工具——GT、、Emmagee
- HTML及相关知识汇总
- 盘点15个搞笑的程序员段子
- paypal简单分享
- 截图工具因为计算机无法使用,Win7系统自带的截图工具不能用了的解决方法
- 如何使TOOLBOX变成中文名称
- 代码技巧1.类似于登录、注册界面要判断登录账号是不是空,验证码是否正确等,怎么写比较舒服一点?
- 考古绘图中计算机的铺助应用,CAD和3D打印技术在文物考古中的应用研究
- App开发用什么软件?零基础也可以制作App
- 免疫算法求解多元函数论文
- Wcf实现IServiceBehavior拓展机制
热门文章
- Linux /usr/bin与/usr/local/bin区别
- 解决go包管理代理网址无法访问:proxy.golang.org 换成goproxy.cn
- K8S报错:controller-manager Unhealthy Get http://127.0.0.1:10252/healthz: dial tcp 127.0.0.1:10252
- arthas使用示例:trace追踪方法调用路径及统计方法耗时
- MySQL索引相关的数据结构和算法
- Collections工具类常用API使用示例
- 强化学习5——价值函数近似(VFA)
- 最优化——线性规划总结2(单纯形法问题总结,检验数为0和退化)
- emwin自定义消息问题
- pytorch指定用多张显卡训练_Pytorch多GPU训练