我的家園

          我的家園

          本文給出兩個函數:

             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. }  

           


           


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


          網站導航:
           
          主站蜘蛛池模板: 西平县| 榆林市| 新野县| 儋州市| 八宿县| 楚雄市| 武穴市| 集安市| 佛坪县| 廊坊市| 德安县| 永州市| 普格县| 安康市| 汉阴县| 甘谷县| 额敏县| 渭南市| 灵川县| 遂溪县| 咸宁市| 淮南市| 朔州市| 垫江县| 屯昌县| 临沂市| 当涂县| 且末县| 鲁山县| 永年县| 北碚区| 宝山区| 珲春市| 江城| 天台县| 镇巴县| 迁安市| 颍上县| 岑溪市| 广南县| 兴海县|