-
深切懂得Java:内省(Introspector)
添加时间:2013-6-3 点击量:一些概念:
内省(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 block
e.printStackTrace();
}
}
}输出:
get userName:peida
set userName:wong
get userName:wong
set userName:alan
get userName:alan
java.lang.IllegalArgumentException: argument type mismatch
at 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)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 mismatch
at 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申明:
获得属性的值,例如,BeanUtils.getProperty(userInfo,userName),返回字符串
设置属性的值,例如,BeanUtils.setProperty(userInfo,age,8),参数是字符串或根蒂根基类型主动包装。设置属性的值是字符串,获得的值也是字符串,不是根蒂根基类型。 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();
}
}
}PropertyUtils类和BeanUtils不合在于,运行getProperty、setProperty操纵时,没有类型转换,应用属性的原有类型或者包装类。
无论对感情还是对生活,“只要甜不要苦”都是任性而孩子气的,因为我们也不完美,我们也会伤害人。正因为我们都不完美,也因为生活从不是事事如意,所以对这些“瑕疵”的收纳才让我们对生活、对他人的爱变得日益真实而具体。—— 汪冰《世界再亏欠你,也要敢于拥抱幸福》