豆沙包

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

          通過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 閱讀(1037) 評論(0)  編輯  收藏 所屬分類: Reflection

          主站蜘蛛池模板: 和顺县| 海阳市| 策勒县| 泰宁县| 清水河县| 格尔木市| 永兴县| 阳曲县| 松原市| 钟山县| 类乌齐县| 繁昌县| 华蓥市| 金沙县| 扎囊县| 卓尼县| 连南| 文安县| 体育| 昭苏县| 桃园市| 绥中县| 张家川| 田东县| 奉新县| 顺平县| 剑河县| 合肥市| 洛扎县| 修水县| 永靖县| 庆安县| 南木林县| 淮安市| 天祝| 兴和县| 邻水| 榆林市| 台南县| 东丰县| 友谊县|