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

javac fails to compile cast class<generic> to class <? extends generic <?>>

XMLWordPrintable

    • windows_xp

      FULL PRODUCT VERSION :
      C:\Program Files\Far>java -version
      java version " 1.7.0_09 "
      Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
      Java HotSpot(TM) Client VM (build 23.5-b02, mixed mode, sharing)

      ADDITIONAL OS VERSION INFORMATION :
      windows xp

      A DESCRIPTION OF THE PROBLEM :
      Javac forbids cast Class<Generic> be cast to Class <? extends Generic<?>>

      In turn, is Class<Generic> probably distinct from Class<? extends Generic<?>> (given that their erasures are the same) ?

      In turn, is 'Generic' probably distinct from '? extends Generic<?>>' ?

      No, because |Generic| <: |Generic<?>|.

      (JLS3 was not clear on this point. If both type arguments were ground types, JLS3 could prove them distinct and stop the cast, e.g. Class<String> can never be cast to Class<Integer> because Class<String> is distinct from Class<Integer> because String is distinct from Integer. However, JLS3 could not handle one or two wildcard type arguments. JLS7 takes the upper bound of a wildcard type argument - Generic<?> - and considers it against the ground type argument - Generic - to conclude that the type arguments are basically related.)

      Therefore, there is no need for a compile-time error.

      Since Class<Generic> is not a subtype of Class<? extends Generic<?>>, the cast is unchecked, and a compile-time unchecked warning is due.

      Alex




      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      compile provided sample code

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      no errors
      ACTUAL -
      errors

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      javac:
      Casting.java:4: error: inconvertible types
                        Class<? extends Generic<?>> generic = (Class<? extends
      Generic<?>>) Generic.class;

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      class Generic<T> {}
      public class Casting {
           void test() {
               Class<? extends Generic<?>> generic = (Class<? extends Generic<?>>) Generic.class;
            }
      }


      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      compile code with Eclipse Juno

            dlsmith Dan Smith
            coffeys Sean Coffey
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: