午夜拍鍵驚奇
          子夜 編程 代碼與我同在
          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 ^ 閱讀(521) 評(píng)論(0)  編輯  收藏 所屬分類: Java 點(diǎn)滴
          主站蜘蛛池模板: 获嘉县| 确山县| 黄骅市| 凤阳县| 景宁| 宿松县| 乐平市| 宜阳县| 修文县| 平谷区| 平泉县| 江阴市| 历史| 民勤县| 通江县| 泰州市| 乐东| 武陟县| 偏关县| 广州市| 秀山| 昆山市| 象州县| 高清| 罗山县| 略阳县| 云浮市| 甘谷县| 乌拉特前旗| 永州市| 高雄县| 集安市| 崇明县| 肇庆市| 广水市| 上高县| 广昌县| 芜湖市| 呼伦贝尔市| 灵山县| 德兴市|