深入理解Java:內省(Introspector)

來源:互聯網
上載者:User

標籤:email   org   pyc   dac   參數   調用   資料   方法   模組   

內省(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:peidaset userName:wongget userName:wongset userName:alanget userName:alanjava.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) 

  說明: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:peidaget userName:peidaset age:18get age:18get userName type:java.lang.Stringget age type:java.lang.String8java.lang.IntegerException 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

  說明:

  1.獲得屬性的值,例如,BeanUtils.getProperty(userInfo,"userName"),返回字串
  2.設定屬性的值,例如,BeanUtils.setProperty(userInfo,"age",8),參數是字串或基本類型自動封裝。設定屬性的值是字串,獲得的值也是字串,不是基本類型。   3.BeanUtils的特點:
    1). 對基礎資料型別 (Elementary Data Type)的屬性的操作:在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

深入理解Java:內省(Introspector)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.