我的家園

          我的家園

          本文給出兩個函數:

             BeanUtils.getFieldValue(object,propertyName);//取出object對象中的propertyName屬性的值.propertyName只能是object所在類中定義的,而不是其基類定義的

                     BeanUtils.getFieldValueInAllSuper(object,propertyName);//);//取出object對象中的propertyName屬性的值.propertyName包括在object所在類的基類中定義的屬性

           

            看代碼:

             

          1. public class BeanUtils {  
          2.   
          3.     
          4.     /** 
          5.      * 獲取當前類聲明的private/protected變量 
          6.      */  
          7.     static public Object getFieldValue(Object object, String propertyName)  
          8.             throws IllegalAccessException, NoSuchFieldException {  
          9.         Assert.notNull(object);  
          10.         Assert.hasText(propertyName);  
          11.         Field field = object.getClass().getDeclaredField(propertyName);  
          12.         field.setAccessible(true);  
          13.   
          14.         return field.get(object);  
          15.     }  
          16.     /** 
          17.      * zhangpf :因為getFieldValue()方法,無法讀取super class的屬性的值; 
          18.      *                  所以本方法做出擴展,允許讀取super class的屬性的值; 
          19.      * @param object 
          20.      * @param propertyName 
          21.      * @return 
          22.      * @throws IllegalAccessException 
          23.      * @throws NoSuchFieldException 
          24.      */  
          25.     public static Object getFieldValueInAllSuper(Object object, String propertyName)  
          26.             throws IllegalAccessException, NoSuchFieldException {  
          27.         Assert.notNull(object);  
          28.         Assert.hasText(propertyName);  
          29.         Class claszz=object.getClass();  
          30.         Field field = null;  
          31.           
          32.         do  
          33.         {     
          34.             try{  
          35.                 field = claszz.getDeclaredField(propertyName);  
          36.             }  
          37.             catch(NoSuchFieldException e)  
          38.             {  
          39.                 //e.printStackTrace();  
          40.                 field=null;  
          41.             }  
          42.             claszz=claszz.getSuperclass();  
          43.         }  
          44.         while(field==null&&claszz!=null);  
          45.           
          46.         if(field==nullreturn null;  
          47.    
          48.         field.setAccessible(true);  
          49.         return field.get(object);  
          50.     }  
          51. }  

           


           


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 腾冲县| 葵青区| 同仁县| 旬邑县| 秦安县| 淄博市| 长春市| 甘孜县| 洞头县| 丰顺县| 张家界市| 邳州市| 泸溪县| 蓬溪县| 呈贡县| 邵阳市| 威信县| 蓝田县| 和静县| 攀枝花市| 鸡东县| 蓬莱市| 武川县| 灵武市| 宝坻区| 都匀市| 鄂托克旗| 北安市| 筠连县| 厦门市| 南华县| 衡水市| 东兰县| 甘德县| 铁岭县| 平果县| 浪卡子县| 宜兰县| 塔城市| 温宿县| 黑河市|