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

Wrong handling of generic when using varargs

XMLWordPrintable

    • x86
    • windows_xp

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

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows XP [Versione 5.1.2600]

      A DESCRIPTION OF THE PROBLEM :
      When using generics in varargs and no parameter is explicitly passed to the API, the compiler produces a wrong output which causes a java.lang.ClassCastException to be thrown.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      public class Foo
      {
          public static <T> T[] foo(T... o)
          {
              return o;
          }

          public static void main(String[] args)
          {
              String[] s = foo();
              System.out.println(s);
          }
      }


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      [Ljava.lang.String;@19821f
      ACTUAL -
      Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      public class Foo
      {
          public static <T> T[] foo(T... o)
          {
              return o;
          }

          public static void main(String[] args)
          {
              String[] s = foo();
              System.out.println(s);
          }
      }

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

      CUSTOMER SUBMITTED WORKAROUND :
      Never use foo() without specifying any parameter.

            mcimadamore Maurizio Cimadamore
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: