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

Javac generates an incorrect cast for an inherited generic array

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Closed
    • Priority: P4
    • Resolution: Not an Issue
    • Affects Version/s: 16
    • Fix Version/s: None
    • Component/s: tools
    • Subcomponent:
    • CPU:
      generic
    • OS:
      generic

      Description

      A DESCRIPTION OF THE PROBLEM :
      When a superclass defines an array with a generic type which can be inherited by a subclass, and the subclass attempts to access it, javac generates an incorrect cast to the array instead of a cast to the accessed elements.

      I have checked earlier versions of javac, back to JDK11, and it has the same problem.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run the provided example. An exception is thrown from the subclass 'get' method.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      No exception is expected.
      ACTUAL -
      Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader 'bootstrap')
              at Bug$Sub.get(Bug.java:20)
              at Bug.main(Bug.java:3)

      ---------- BEGIN SOURCE ----------
      public class Bug<A> {
          public static void main(String[] args) {
              new Sub().get(0);
          }

          protected final A[] elements;

          @SuppressWarnings("unchecked")
          public Bug() {
              elements = (A[]) new Object[10];
          }

          protected A doGet(int i) {
              return elements[i];
          }

          static class Sub extends Bug<String> {
              public String get(int i) {
                  // return doGet(i); workaround
                  return elements[i];
              }
          }
      }

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

      CUSTOMER SUBMITTED WORKAROUND :
      The superclass must define a method to access the array elements directly, and the subclass must call that instead.

      FREQUENCY : always


        Attachments

          Activity

            People

            Assignee:
            jlahoda Jan Lahoda
            Reporter:
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: