午夜拍鍵驚奇
          子夜 編程 代碼與我同在
          posts - 48,comments - 118,trackbacks - 79

          一、illegal forward refrence

          前天寫一個(gè)類時(shí)遇到一個(gè)很眼生的編譯錯(cuò)誤(問題簡化后):

          1punlic final class Constants{
          2  public static int VAR2 = VAR1 + 1;
          3  public static int VAR1 = 1;
          4}

          編譯時(shí)出錯(cuò)(第2行):

          illegal forward refrence

          仔細(xì)一想,是因?yàn)閂AR2引用的VAR1在VAR2之后定義,看來在Java中定義static變量時(shí)應(yīng)遵循“聲明先于使用”的原則。

           

          二、static塊

          還是上一個(gè)類,VAR1和VAR2定義成final,值存在一個(gè)properties文件中,在使用前必須將值load進(jìn)來:

          System.getProperties().load(new FileInputStream("constants.properties"));

          于是將上面的代碼放在static塊中:

          punlic final class Constants{
            
          static{
              System.getProperties().load(
          new FileInputStream("constants.properties"));
            }


            
          public static final int VAR2 = System.getProperties().getProperty("var2");

            
          public static final int VAR1 = System.getProperties().getProperty("var1");
          }


          但在運(yùn)行時(shí)VAR1和VAR2沒有被賦值,debug后發(fā)現(xiàn)static塊根本沒有執(zhí)行。于是頓悟:final變量在編譯時(shí)便被編譯器計(jì)算、賦值,因此在運(yùn)行時(shí)沒有必要執(zhí)行static塊。

          posted on 2005-08-04 12:27 ^ Mustang ^ 閱讀(526) 評(píng)論(0)  編輯  收藏 所屬分類: Java 點(diǎn)滴
          主站蜘蛛池模板: 平武县| 水城县| 利川市| 静安区| 双辽市| 玛多县| 峡江县| 吉木乃县| 宜州市| 定襄县| 合川市| 甘孜县| 阿拉尔市| 卢氏县| 嘉荫县| 五峰| 庄河市| 孙吴县| 金坛市| 广宗县| 化隆| 卓尼县| 陆良县| 安塞县| 田阳县| 阿鲁科尔沁旗| 乐业县| 广灵县| 彭阳县| 庆云县| 西藏| 封开县| 阜城县| 平和县| 景谷| 鄂尔多斯市| 贡山| 石棉县| 抚顺市| 泰兴市| 隆回县|