Web 使用反射獲得一個對象的所有get方法:

來源:互聯網
上載者:User

標籤:類測試   對象   注意   字串方法   錯誤   使用   set   包括   method   

問題描述:
由於想知道request中包含哪些getter方法,就想通過反射進行遍曆,然後輸出,結果異常,異常資訊:

問題代碼:
        try {                        outGetter(request);                    } catch (IntrospectionException e) {                        e.printStackTrace();     }public void outGetter(Object obj) throws IntrospectionException    {        Class<?> clazz = obj.getClass();        //獲得所有的屬性        Field[] fields = clazz.getDeclaredFields();                for(Field field:fields)        {            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);            Method method = pd.getReadMethod();            System.out.println(method);        }}
問題分析:
IntrospectionException: 在 Introspection 期間發生異常時拋出異常。
  典型的 cause 包括:無法將字串類名稱映射到 Class 對象、無法解析字串方法名,或者指定對其用途而言具有錯誤類型簽名的方法名稱。
而Method not found:isRequest則表示isRequest方法找不到,分析遍曆代碼,可知:  public PropertyDescriptor(String propertyName, Class<?> beanClass) throws IntrospectionException  
  通過調用 getFoo 和 setFoo 存取方法,為符合標準 Java 約定的屬性構造一個 PropertyDescriptor。
  因此如果參數名為 "fred",則假定 writer 方法為 "setFred",reader 方法為 "getFred"(對於 boolean 屬性則為 "isFred")。
  注意,屬性名稱應該以小寫字母開頭,而方法名稱中的首寫字母將是大寫的。  參數:propertyName - 屬性的編程名稱。 beanClass - 目標 bean 的 Class 對象。例如 sun.beans.OurButton.class。  拋出:IntrospectionException - 如果在內省期間發生異常。

得到結論:通過反射輸出對象的getter方法,前提是對象中的屬性和getter一一對應
//通過實體類測試一下
public class User { private String username; private String pwd;

public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; }} try { User user = new User(); outGetter(user); } catch (IntrospectionException e) { e.printStackTrace;  ·  }
結果輸出:

問題解決:
原因找到了,那麼回到最初的問題上來,如何獲得對象的所有get方法?
    public void outGetter(Object obj) throws IntrospectionException    {        Class<?> clazz = obj.getClass();                //返回此class對象所表示的類的所有public方法        Method[] methods = clazz.getMethods();                for(Method m:methods)        {              System.out.println(string);        }        }
輸出結果:

既然得到了所有的方法,那麼能不能對這些方法進行篩選呢?

m.toString().contains("get"):判斷方法中是否含有get,如果有,輸出
m.toString().substring(m.toString().lastIndexOf(".")+1):將合格方法名進行處理,只截取最後的方法名
    public void outGetter(Object obj) throws IntrospectionException    {        Class<?> clazz = obj.getClass();                //返回此class對象所表示的類的所有public方法        Method[] methods = clazz.getMethods();                for(Method m:methods)        {            //需要進一步篩選            //截取最後的方法名                         if(m.toString().contains("get"))            {                String string = m.toString().substring(m.toString().lastIndexOf(".")+1);                System.out.println(string);            }                        }        }

問題總結:
PropertyDescriptor類:PropertyDescriptor類表示JavaBean類通過儲存空間匯出一個屬性。主要方法:      1.  getReadMethod(),獲得用於讀取屬性值的方法      2.  getWriteMethod(),獲得用於寫入屬性值的方法
通過反射輸出對象的getter方法,前提是對象中的屬性和getter一一對應

Web 使用反射獲得一個對象的所有get方法:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.