Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8295018

False positive of "Illegal forward reference" compile-time error

XMLWordPrintable

    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      Normally, we may initialize static field of a class in the static block, even before that static field's declaration. But after that initialization, in the case of trying using this static field, the compiler report "Illegal forward reference" despite that the static field has already been initialized.

      But if you use class-name style access, the error disappears.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Try to compiler the following code:

      class Test {
          static {
              b = 1;
              Integer a = b; // Illegal forward reference
          }
          static Integer b;

          public static void main(String[] args) {}
      }

      The compiler report "Illegal forward reference" on "Integer a = b", but b actually was initialized above.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      No "Illegal forward reference" error reported
      ACTUAL -
      Error "Illegal forward reference" is reported

      ---------- BEGIN SOURCE ----------
      class Test {
          static {
              b = 1;
              Integer a = b; // Illegal forward reference
          }
          static Integer b;

          public static void main(String[] args) {}
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Use class-name style access to the static field:

      class Test {
          static {
              b = 1;
              Integer a = Test.b; // OK
          }
          static Integer b;

          public static void main(String[] args) {}
      }

      FREQUENCY : always


            adev Anupam Dev
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: