深入理解Java:内省(Introspector)
本文内容纲要:
一些概念:
内省(Introspector)是Java语言对JavaBean类属性、事件的一种缺省处理方法。
JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(ValueObject),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。
例如类UserInfo:
packagecom.peidasoft.Introspector;
publicclassUserInfo{
privatelonguserId;
privateStringuserName;
privateintage;
privateStringemailAddress;
publiclonggetUserId(){
returnuserId;
}
publicvoidsetUserId(longuserId){
this.userId=userId;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
publicStringgetEmailAddress(){
returnemailAddress;
}
publicvoidsetEmailAddress(StringemailAddress){
this.emailAddress=emailAddress;
}
}
在类UserInfo中有属性userName,那我们可以通过getUserName,setUserName来得到其值或者设置新的值。通过getUserName/setUserName来访问userName属性,这就是默认的规则。JavaJDK中提供了一套API用来访问某个属性的getter/setter方法,这就是内省。
JDK内省类库:
PropertyDescriptor类:
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
1.getPropertyType(),获得属性的Class对象;
2.getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
3.hashCode(),获取对象的哈希值;
4.setReadMethod(MethodreadMethod),设置用于读取属性值的方法;
5.setWriteMethod(MethodwriteMethod),设置用于写入属性值的方法。
实例代码如下:
packagecom.peidasoft.Introspector;
importjava.beans.BeanInfo;
importjava.beans.Introspector;
importjava.beans.PropertyDescriptor;
importjava.lang.reflect.Method;
publicclassBeanInfoUtil{
publicstaticvoidsetProperty(UserInfouserInfo,StringuserName)throwsException{
PropertyDescriptorpropDesc=newPropertyDescriptor(userName,UserInfo.class);
MethodmethodSetUserName=propDesc.getWriteMethod();
methodSetUserName.invoke(userInfo,"wong");
System.out.println("setuserName:"+userInfo.getUserName());
}
publicstaticvoidgetProperty(UserInfouserInfo,StringuserName)throwsException{
PropertyDescriptorproDescriptor=newPropertyDescriptor(userName,UserInfo.class);
MethodmethodGetUserName=proDescriptor.getReadMethod();
ObjectobjUserName=methodGetUserName.invoke(userInfo);
System.out.println("getuserName:"+objUserName.toString());
}
}
Introspector类:
将JavaBean中的属性封装起来进行操作。在程序把一个类当做JavaBean来看,就是调用Introspector.getBeanInfo()方法,得到的BeanInfo对象封装了把这个类当做JavaBean看的结果信息,即属性的信息。
getPropertyDescriptors(),获得属性的描述,可以采用遍历BeanInfo的方法,来查找、设置类的属性。具体代码如下:
packagecom.peidasoft.Introspector;
importjava.beans.BeanInfo;
importjava.beans.Introspector;
importjava.beans.PropertyDescriptor;
importjava.lang.reflect.Method;
publicclassBeanInfoUtil{
publicstaticvoidsetPropertyByIntrospector(UserInfouserInfo,StringuserName)throwsException{
BeanInfobeanInfo=Introspector.getBeanInfo(UserInfo.class);
PropertyDescriptor[]proDescrtptors=beanInfo.getPropertyDescriptors();
if(proDescrtptors!=null&&proDescrtptors.length>0){
for(PropertyDescriptorpropDesc:proDescrtptors){
if(propDesc.getName().equals(userName)){
MethodmethodSetUserName=propDesc.getWriteMethod();
methodSetUserName.invoke(userInfo,"alan");
System.out.println("setuserName:"+userInfo.getUserName());
break;
}
}
}
}
publicstaticvoidgetPropertyByIntrospector(UserInfouserInfo,StringuserName)throwsException{
BeanInfobeanInfo=Introspector.getBeanInfo(UserInfo.class);
PropertyDescriptor[]proDescrtptors=beanInfo.getPropertyDescriptors();
if(proDescrtptors!=null&&proDescrtptors.length>0){
for(PropertyDescriptorpropDesc:proDescrtptors){
if(propDesc.getName().equals(userName)){
MethodmethodGetUserName=propDesc.getReadMethod();
ObjectobjUserName=methodGetUserName.invoke(userInfo);
System.out.println("getuserName:"+objUserName.toString());
break;
}
}
}
}
}
通过这两个类的比较可以看出,都是需要获得PropertyDescriptor,只是方式不一样:前者通过创建对象直接获得,后者需要遍历,所以使用PropertyDescriptor类更加方便。
使用实例:
packagecom.peidasoft.Introspector;
publicclassBeanInfoTest{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
UserInfouserInfo=newUserInfo();
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(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
输出:
getuserName:peida
setuserName:wong
getuserName:wong
setuserName:alan
getuserName:alan
java.lang.IllegalArgumentException:argumenttypemismatch
atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)
atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
atjava.lang.reflect.Method.invoke(Method.java:597)
atcom.peidasoft.Introspector.BeanInfoUtil.setProperty(BeanInfoUtil.java:14)
atcom.peidasoft.Introspector.BeanInfoTest.main(BeanInfoTest.java:22)
**说明:**BeanInfoUtil.setProperty(userInfo,"age");报错是应为age属性是int数据类型,而setProperty方法里面默认给age属性赋的值是String类型。所以会爆出argumenttypemismatch参数类型不匹配的错误信息。
**BeanUtils工具包:**
由上述可看出,内省操作非常的繁琐,所以所以Apache开发了一套简单、易用的API来操作Bean的属性——BeanUtils工具包。
BeanUtils工具包:下载:http://commons.apache.org/beanutils/注意:应用的时候还需要一个logging包http://commons.apache.org/logging/
使用BeanUtils工具包完成上面的测试代码:
packagecom.peidasoft.Beanutil;
importjava.lang.reflect.InvocationTargetException;
importorg.apache.commons.beanutils.BeanUtils;
importorg.apache.commons.beanutils.PropertyUtils;
importcom.peidasoft.Introspector.UserInfo;
publicclassBeanUtilTest{
publicstaticvoidmain(String[]args){
UserInfouserInfo=newUserInfo();
try{
BeanUtils.setProperty(userInfo,"userName","peida");
System.out.println("setuserName:"+userInfo.getUserName());
System.out.println("getuserName:"+BeanUtils.getProperty(userInfo,"userName"));
BeanUtils.setProperty(userInfo,"age",18);
System.out.println("setage:"+userInfo.getAge());
System.out.println("getage:"+BeanUtils.getProperty(userInfo,"age"));
System.out.println("getuserNametype:"+BeanUtils.getProperty(userInfo,"userName").getClass().getName());
System.out.println("getagetype:"+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(IllegalAccessExceptione){
e.printStackTrace();
}
catch(InvocationTargetExceptione){
e.printStackTrace();
}
catch(NoSuchMethodExceptione){
e.printStackTrace();
}
}
}
运行结果:
setuserName:peida
getuserName:peida
setage:18
getage:18
getuserNametype:java.lang.String
getagetype:java.lang.String
8
java.lang.Integer
Exceptioninthread"main"java.lang.IllegalArgumentException:Cannotinvokecom.peidasoft.Introspector.UserInfo.setAge
onbeanclass'classcom.peidasoft.Introspector.UserInfo'-argumenttypemismatch-hadobjectsoftype"java.lang.String"
butexpectedsignature"int"
atorg.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2235)
atorg.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:2151)
atorg.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1957)
atorg.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:2064)
atorg.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:858)
atcom.peidasoft.orm.Beanutil.BeanUtilTest.main(BeanUtilTest.java:38)
Causedby:java.lang.IllegalArgumentException:argumenttypemismatch
atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)
atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
atjava.lang.reflect.Method.invoke(Method.java:597)
atorg.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2170)
...5more
说明:
1.获得属性的值,例如,BeanUtils.getProperty(userInfo,"userName"),返回字符串
2.设置属性的值,例如,BeanUtils.setProperty(userInfo,"age",8),参数是字符串或基本类型自动包装。设置属性的值是字符串,获得的值也是字符串,不是基本类型。3.BeanUtils的特点:
1).对基本数据类型的属性的操作:在WEB开发、使用中,录入和显示时,值会被转换成字符串,但底层运算用的是基本类型,这些类型转到动作由BeanUtils自动完成。
2).对引用数据类型的属性的操作:首先在类中必须有对象,不能是null,例如,privateDatebirthday=newDate();。操作的是对象的属性而不是整个对象,例如,BeanUtils.setProperty(userInfo,"birthday.time",111111);
packagecom.peidasoft.Introspector;
importjava.util.Date;
publicclassUserInfo{
privateDatebirthday=newDate();
publicvoidsetBirthday(Datebirthday){
this.birthday=birthday;
}
publicDategetBirthday(){
returnbirthday;
}
}
packagecom.peidasoft.Beanutil;
importjava.lang.reflect.InvocationTargetException;
importorg.apache.commons.beanutils.BeanUtils;
importcom.peidasoft.Introspector.UserInfo;
publicclassBeanUtilTest{
publicstaticvoidmain(String[]args){
UserInfouserInfo=newUserInfo();
try{
BeanUtils.setProperty(userInfo,"birthday.time","111111");
Objectobj=BeanUtils.getProperty(userInfo,"birthday.time");
System.out.println(obj);
}
catch(IllegalAccessExceptione){
e.printStackTrace();
}
catch(InvocationTargetExceptione){
e.printStackTrace();
}
catch(NoSuchMethodExceptione){
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/peida/archive/2013/06/03/3090842.html