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.
Line
return (T)dataMap.get(value);
generates an Unchecked cast warning and, per specification, the presence of any such warning makes your code type-unsafe. The ClassCastException
occurs the first time you try to assign the type-unsafe result into a variable of the wrong type because this is the first time the compiled code has a type check.
Note that Eclipse's compiler inserts more type checks than mandated by the JLS so, if you compile within Eclipse, the hashMap.put
invocation fails with CCE
. The compiler knows that this call must have two String
arguments and so is in a position to insert the type checks before the actual method call.
Exactly as you are guessing, if you replace the generic T
with the specific String
, then the type check occurs at that point—and fails.
Compiler depends on type safety to make assumptions and do transformations/optimizations. Unfortunately the type safety can be subverted through unchecked cast. If your program contains incorrect unchecked cast, it is unclear what the compiler should do. Ideally it should make a runtime check at the exact point of unchecked cast, in your example, when Object
is casted to T
. But that is impossible, due to erasure, which is not exactly part of the type system.
Everywhere else in your example, types are sound, so compiler can assume that getValue()
really returns a String
, it is unnecessary to double check. But it's also legal to do the check, as Eclipse compiler does (probably because it assigns the return value to a String
local temp variable).
So the bad news is, if your program contains incorrect unchecked cast, its behavior is undefined.... So make sure all your unchecked casts are correct, through rigorous reasoning.
A good practice is to check all unchecked casts so you can legitimately suppress the unchecked warning. For example
<T> T getValue(Map<String, Object> dataMap, String value, Class<T> type)
{
Object value = dataMap.get(value);
if(value!=null && !type.isInstance(value)) // check!
throw new ClassCastException();
@SuppressWarning("unchecked")
T t = (T)value; // this is safe, because we've just checked
return t;
}
See my answer to a similar question: Lazy class cast in Java?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With