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

Incorrect "Type mismatch" reported for generic cast of class literals.

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 7
    • specification
    • x86
    • windows_7

      FULL PRODUCT VERSION :
      java version "1.7.0"
      Java(TM) SE Runtime Environment (build 1.7.0-b147)
      Java HotSpot(TM) 64-Bit Server VM (build 21.0-b17, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows [Version 6.1.7601]

      A DESCRIPTION OF THE PROBLEM :
      Attempting to compile this statement results in a "Type mismatch" error:

      Class<List<String>> stringListType = List.class;

      The compiler error specifically states "cannot convert from Class<List> to Class<List<String>>". This is a distinctly false statement. The following adjustment compiles with warnings but no errors:

      Class<List<String>> stringListType = (Class<List<String>>) (Class<?>) List.class;

      The code runs correctly, because the generic types are not present in the bytecode. So in fact the compiler "can convert from Class<List> to Class<List<String>>".

      Type erasure causes all generic tokens on a variable declaration of type Class to be fully meaningless in regards to cast compatibility. Therefore, every possibly generic qualification of a variable declaration of type Class should be assignable from a class literal with a matching base type. For example, this statement should compile with no errors or warnings:

      Class<Complicated<Nested<Type<Parameters>>>> complicatedType = Complicated.class;

      The compiler can do this. It is correct and also quite useful.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Attempt to compile the syntactically meaningful statement:

      Class<List<String>> stringListType = List.class;


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The statement should compile with no errors. This statement can be compiled, violates no rules, and causes no problems.
      ACTUAL -
      The compiler reports "Type mismatch: cannot convert from Class<List> to Class<List<String>>"


      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      Type mismatch: cannot convert from Class<List> to Class<List<String>>

      REPRODUCIBILITY :
      This bug can be reproduced always.

      CUSTOMER SUBMITTED WORKAROUND :
      Add a painfully cumbersome pair of casts to the statement:

      Class<List<String>> stringListType = (Class<List<String>>) (Class<?>) List.class;

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

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: