Give the following code:
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<>();
HashMap<String, Object> dataMap = new HashMap<>();
dataMap.put("longvalue", 5L);
class TestMethodHolder {
<T> T getValue(Map<String, Object> dataMap, String value) {
return (T)dataMap.get(value);
}
}
hashMap.put("test", new TestMethodHolder().<String>getValue(dataMap, "longvalue"));
String value = hashMap.get("test"); // ClassCastException occurs HERE
System.out.println(value);
}
It is not surprising to me that this code compiles, but rather that the ClassCastException occurs on the get line as opposed to the put line above it, though I do have an educated guess as to what what may be occurring. Since generic types are erased during runtime, the cast in getValue() actually never occurs at runtime and is effectively a cast to Object. If the method would be implemented below as follows, then the runtime cast would occur and it would fail on the put line (as expected). Can anyone confirm this?
class TestMethodHolder {
String getValue(Map<String, Object> dataMap, String value) {
return (String)dataMap.get(value);
}
}
Is this a known flaw or oddity of using generics? Is it bad practice then to use the <> notation when calling methods?
Edit:
I am using the default Oracle JDK 1.7_03.
Another implied question from above: Is the cast in the original getValue STILL occurring at runtime but the cast is actually to Object - or is the compiler smart enough to remove this cast from not occurring at runtime at all? This might explain the difference of where the ClassCastException is occurring that people are noticing when running it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…