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

Inconsistent compilation behavior across Java versions

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      javac 1.8.0_461

      java version "1.8.0_461"
      Java(TM) SE Runtime Environment (build 1.8.0_461-b11)
      Java HotSpot(TM) 64-Bit Server VM (build 25.461-b11, mixed mode)

      A DESCRIPTION OF THE PROBLEM :
      javac shows inconsistent compilation behavior for the same code across different Java versions when casting generic type variables to primitive types with instanceof check.

      The same Java code compiles successfully with javac 11, 17, and 21, but fails with javac 8.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Compling following code using javac in JDK8.
      ```
      javac Test.java
      ```

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The compilation should be successful.
      ACTUAL -
      The compilation fail with an error message
      ```
      Test.java:9: error: incompatible types: U cannot be converted to int
                  int intValue = (int) value;
                                       ^
        where U is a type-variable:
          U extends Object declared in method <U>executeWithNoexcept(U)
      1 error
      ```

      ---------- BEGIN SOURCE ----------
      public class Test {
          public static void main(String[] strArr) {
          }
      }

      class TemplateClass<T> {
          public static <U> void executeWithNoexcept(U value) {
              if (value instanceof Integer) {
                  int intValue = (int) value;
              }
          }
      }
      ---------- END SOURCE ----------

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: