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

          一、illegal forward refrence

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

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

          編譯時出錯(第2行):

          illegal forward refrence

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

           

          二、static塊

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

          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");
          }


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

          posted on 2005-08-04 12:27 ^ Mustang ^ 閱讀(526) 評論(0)  編輯  收藏 所屬分類: Java 點滴
          主站蜘蛛池模板: 财经| 平乐县| 朝阳市| 乡城县| 莱州市| 河源市| 佛教| 光山县| 双江| 勃利县| 衡南县| 高陵县| 宁蒗| 无锡市| 龙南县| 黑河市| 枣强县| 尉犁县| 敦煌市| 鄢陵县| 洞头县| 富阳市| 高邑县| 陇南市| 西平县| 莎车县| 新兴县| 通化市| 延长县| 芦溪县| 通渭县| 林甸县| 东光县| 中牟县| 鸡泽县| 泰州市| 仪陇县| 汶川县| 西藏| 石景山区| 东至县|