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

Compiler does not fail on a incorrect generic type passed as argument

XMLWordPrintable

    • x86_64
    • generic

      A DESCRIPTION OF THE PROBLEM :
      When instantiating a generic class with no type parameter, the compiler seems to allow passing generics of incorrect types to methods that have (unrelated) generic class arguments.

      In the provided source code, the Test<T> class has a method that takes a List<Integer> as argument.
      When Test is instantiated without any type parameter, the compiler seems to accept any List and does not detect an error when e.g. a List<String> is passed as argument.

      The source code below will not throw an error but instead will fail at runtime with a class cast exception. I would have expected that this would throw a compile error the same way as it would if Test were not generic.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Compile provided code.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Compilation fails.
      ACTUAL -
      Compilation does not fail.

      ---------- BEGIN SOURCE ----------
      class Main {
        private static class Test<T> {
          void method( List<Integer> a ) {
            Integer s = a.get( 0 );
          }
        }

        public static void main( String[] args ) {
          List<String> a = Arrays.asList( "1", "2" );
          Test t = new Test();
          t.method( a );
        }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


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

              Created:
              Updated:
              Resolved: