1. 程式人生 > >Web 使用反射獲得一個對象的所有get方法:

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

字符串方法 拋出異常 getmethod esc sub 代碼 pro span con

問題描述:

由於想知道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方法: