豆沙包

          …… …… 所學 所寫 所想 所做 所悟…… ……

          通過Java Reflection 獲取指定static變量的值

          比如:有一個SQLUtil類,是一個Hibernate項目中的用來存儲一系列sql的類,皆為常量。在其它的類中可以根據變量的名稱來索引相應的值,問題在于名稱在另外的類中亦為變量,直接索引是沒有辦法的,但可以透過Java Reflection非常方便的實現。給出的是示意性代碼,相應的Exception處理顯然不夠 elegant
          /*
           * Created on 2005-3-3
           *
           * TODO To change the template for this generated file go to
           * Window - Preferences - Java - Code Style - Code Templates
           
          */

          package reflection;

          /**
           * @author ruby
           *
           * TODO To change the template for this generated type comment go to
           * Window - Preferences - Java - Code Style - Code Templates
           
          */

          public class SQLUtil {
              
          public static final String SELECT_SQL="from Ruby";

          }


          /*
           * Created on 2005-3-3
           *
           * TODO To change the template for this generated file go to
           * Window - Preferences - Java - Code Style - Code Templates
           
          */

          package reflection;

          import java.lang.reflect.Field;

          /**
           * @author ruby
           * 
           * TODO To change the template for this generated type comment go to Window -
           * Preferences - Java - Code Style - Code Templates
           
          */

          public class Manager {

              
          public static String getValue(String sqlName) throws SecurityException,
                      NoSuchFieldException, IllegalArgumentException,
                      IllegalAccessException 
          {

                  Field f 
          = SQLUtil.class.getField(sqlName);

                  
          return f.get(null).toString();
              }


              
          public static void main(String[] args) throws SecurityException,
                      NoSuchFieldException, IllegalArgumentException,
                      IllegalAccessException 
          {
                  System.
          out.println(getValue("SELECT_SQL"));
              }

          }

          posted on 2005-03-04 09:28 carob 閱讀(1032) 評論(0)  編輯  收藏 所屬分類: Reflection

          主站蜘蛛池模板: 尚义县| 靖边县| 阿坝| 崇阳县| 和龙市| 吴堡县| 尚志市| 庄河市| 沙河市| 平乡县| 彰武县| 阜城县| 高尔夫| 万荣县| 历史| 独山县| 休宁县| 大港区| 专栏| 电白县| 冀州市| 修武县| 宣化县| 肥西县| 剑河县| 邵武市| 兴仁县| 永吉县| 名山县| 沈阳市| 石狮市| 长宁县| 上杭县| 博爱县| 南宁市| 台中县| 临夏市| 龙胜| 寻甸| 贡嘎县| 汶川县|