Potential problems with one of Oracle’s Java generics
I'm reviewing a Java generic Oracle path called "effects of type error and bridge methods", and I can't convince myself to give an explanation Curious, I tested the code locally, and I couldn't even reproduce the behavior of tracking interpretation This is the relevant code:
public class Node<T> { public T data; public Node(T data) { this.data = data; } public void setData(T data) { System.out.println("Node.setData"); this.data = data; } } public class MyNode extends Node<Integer> { public MyNode(Integer data) { super(data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } }
Oracle trace declares the following behavior for this snippet:
MyNode mn = new MyNode(5); Node n = mn; // A raw type - compiler throws an unchecked warning n.setData("Hello"); Integer x = mn.data; // Causes a ClassCastException to be thrown.
After type erasure, this code segment should look like the following:
MyNode mn = new MyNode(5); Node n = (MyNode)mn; // A raw type - compiler throws an unchecked warning n.setData("Hello"); Integer x = (String)mn.data; // Causes a ClassCastException to be thrown.
I don't understand the cast or behavior used here When I tried to run this code locally using IntelliJ and Java 7, I encountered this situation:
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;
In other words, the JVM does not allow string to be used with setdata() This is actually intuitive to me, and it agrees with my understanding of generics Since mynode Mn is constructed with integer, the compiler should convert every call to SetData () using integer to ensure type safety (i.e. passing in integer)
Can anyone understand this obvious mistake in the Oracle trail?
Solution
You misread the Oracle page If you read until the end, you will find that it will explain what you are describing
This is not a well written page; The authors say "what happened" when they mean "if this happens, it will happen, but we won't see it." Their language is too loose
Page – key points of bridging approach – explain that the behavior you predict (based on the actual design and implementation of generics) is the real behavior when they "suggest" at the beginning