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

15.9.3: Anonymous inner class can have capture type in supertype

    XMLWordPrintable

Details

    • generic
    • generic

    Description

      A DESCRIPTION OF THE PROBLEM :
      This problem is about anonymous inner classes extending inner classes nested in generic classes when the outer instance has a wildcard in its type. It creates a class whose super class has a capture type as type parameter. That causes multiple problems.
      For one, this can cause heap pollution (without unchecked warnings).
      This also makes javac write out an incorrect type signature, causing a java.lang.reflect.GenericSignatureFormatError when using Class.getGenericSuperclass().

      I originally wrote about this problem in this blog post: http://wouter.coekaerts.be/2018/java-type-system-broken


      ---------- BEGIN SOURCE ----------
      public class CaptureInSuperClass {
        static class Box<A> {
          A a;
          Box(A a) { this.a = a; }

          class Inner {
            void setA(A newA) {
              a = newA;
            }

            A getA() {
              return a;
            }
          }
        }

        static Object prev;
        public static void main(String[] args) {
          Box<String> stringBox = new Box<>("1");
          for (Box<?> box : List.of(stringBox, new Box<>(1))) {
            box.new Inner() {{
              if (prev == null) prev = this;
              else this.getClass().cast(prev).setA(this.getA());
            }};
          }

          // ClassCastException
          String s = stringBox.a;

          // GenericSignatureFormatError
          ((Box<?>)stringBox).new Inner(){}.getClass().getGenericSuperclass();
        }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


      Attachments

        Issue Links

          Activity

            People

              dlsmith Dan Smith
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated: