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

Problem when casting from parametrized type to concrete class

    XMLWordPrintable

Details

    • x86
    • windows_xp

    Description

      FULL PRODUCT VERSION :
      java version "1.6.0"
      Java(TM) SE Runtime Environment (build 1.6.0-b105)
      Java HotSpot(TM) Client VM (build 1.6.0-b105, mixed mode, sharing)

      ADDITIONAL OS VERSION INFORMATION :
      Windows XP Proffesional

      A DESCRIPTION OF THE PROBLEM :
      Can not compile class containing casting from the parametrized type to a concrete type.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Compile following class:

      --------------------------------------------------------------

      import java.util.Comparator;

      public class GenericsComparator <T extends Comparable<T>> implements Comparator<T>{
      public int compare(T o1, T o2) {
      if (o1 instanceof String)
      {
      String s = (String)o1;
      }
      return 0;
      }
      }

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Class should be compilable.
      ACTUAL -
      >javac deleteme\GenericsComparator.java

      deleteme\GenericsComparator.java:8: inconvertible types
      found : T
      required: java.lang.String
                      if (o1 instanceof String)
                          ^
      deleteme\GenericsComparator.java:10: inconvertible types
      found : T
      required: java.lang.String
                              String s = (String)o1;
                                                 ^
      2 errors

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      inconvertible types

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.util.Comparator;

      public class GenericsComparator <T extends Comparable<T>> implements Comparator<T>{
      public int compare(T o1, T o2) {
      if (o1 instanceof String)
      {
      String s = (String)o1;
      }
      return 0;
      }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Explicit cast to Object:

      ------------------------------------------------

      public class GenericsComparator <T extends Comparable<T>> implements Comparator<T>{

      public int compare(T o1, T o2) {
      if ((Object)o1 instanceof String)
      {
      String s = (String)(Object)o1;
      }
      return 0;
      }
      }

      Attachments

        Issue Links

          Activity

            People

              mcimadamore Maurizio Cimadamore
              tyao Ting-Yun Ingrid Yao (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              0 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:
                Imported:
                Indexed: