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

7.5.1: Ignore single-type-import of only top level, not nested, types in same compilation unit

    XMLWordPrintable

Details

    • Verified

    Description

      A DESCRIPTION OF THE PROBLEM :
      JLS 14 §7.5.1 (https://docs.oracle.com/javase/specs/jls/se14/html/jls-7.html#jls-7.5.1) says:
      > If the type imported by the single-type-import declaration is declared in the compilation unit that contains the import declaration, the import declaration is ignored.

      However, it appears javac does *not* consistently ignore the import. For example if the import is for a nested type in the same compilation unit and an access to the type exists where that type is not in scope, then javac compiles that without errors, see code below.

      Or maybe the JLS is a little bit strict here and should be changed to specify that only the import for the top level type is ignored (though I don't know why someone would import that).

      Related (historical) reports:
      - JDK-4081024
      - JDK-4661751
      - JDK-4662489


      ---------- BEGIN SOURCE ----------
      package test;

      /*
       * According to JLS 14 §7.5.1 this should be ignored by the compiler
       * (Note that this should *not* be ignored if it was a static import)
       * > If the type imported by the single-type-import declaration is declared
       * > in the compilation unit that contains the import declaration, the import
       * > declaration is ignored.
       *
       * However, if commented out, the code does not compile because the
       * the import is not actually ignored (see below)
       */
      import test.Outer.InnerB1.InnerB2;

      /*
       * Note that this is ignored as expected, otherwise a compile-time error
       * would occur
       * > If a single-type-import declaration imports a type whose simple name is n,
       * > and the compilation unit also declares a top level type (§7.6) whose simple
       * > name is n, a compile-time error occurs.
       */
      import test.Outer;

      class Outer {
          class InnerA1 {
              class InnerA2 {
                  // This works because InnerB1 is in scope
                  int b1 = InnerB1.i;
                  // This only works due to the import
                  int b2 = InnerB2.i;
              }
          }
          
          static class InnerB1 {
              static int i = 1;
              
              static class InnerB2 {
                  static int i = 1;
              }
          }
      }
      ---------- END SOURCE ----------

      Attachments

        Activity

          People

            abuckley Alex Buckley
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: