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

Incorrect type casts in "Effects of Type Erasure and Bridge Methods" tutorial

XMLWordPrintable

    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      Consider this snippet at https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html:

      "Consider the following code:

      MyNode mn = new MyNode(5);
      Node n = mn; // A raw type - compiler throws an unchecked warning
      n.setData("Hello"); // Causes a ClassCastException to be thrown.
      Integer x = mn.data;
      After type erasure, this code becomes:

      MyNode mn = new MyNode(5);
      Node n = (MyNode)mn; // A raw type - compiler throws an unchecked warning
      n.setData("Hello"); // Causes a ClassCastException to be thrown.
      Integer x = (String)mn.data;"

      The type casts in "After type erasure" are incorrect:
        1. Actual: "Node n = (MyNode)mn;"
            Expected: either "Node n = (Node) mn;" (for illustration purposes) or"Node n = mn;" (preferred) because the compiler doesn't generate any cast here since none is required

        2. Actual: "Integer x = (String)mn.data;",
            Expected: "Integer x = (Integer) mn.data;" because the compiler generates a "24: checkcast #8 // class java/lang/Integer"


      FREQUENCY : always


            rgallard Raymond Gallardo
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: