Reputation: 671
When I execute this I get a ClassCastException on line 9. I'm wondering why the exception happens there. From what I understand about generics, I would expect type inference to cause the exception to be thrown in the try catch.
This is compiled using 1.7.
public class MyClass {
private static Map<String, Object> map = new HashMap<>();
public static void main(String args[]) {
map.put("key", Integer.valueOf(1));
Float c = method("key");
}
public static <T> T method(String k) {
try {
return (T) map.get(k);
} catch (ClassCastException ex) {
System.out.println(ex);
return null;
}
}
}
Is there any way to get the exception to be thrown within the method? I've seen usages below but I don't have access to the Float.class at time of call.
method(Float.class, "key")
public static <T> T method(Class<T> clazz, String k) {
try {
return clazz.cast(map.get(k));
...
Upvotes: 0
Views: 73
Reputation: 1300
This is because of type erasure
Actually your code after erasure will look as:
public static void main(String args[]) {
map.put("key", Integer.valueOf(1));
Float c = (Float) method("key");
}
public static Object method(String k) {
try {
return map.get(k);
} catch (ClassCastException ex) {
System.out.println(ex);
return null;
}
}
That's why you got exception in a line which wasn't expected by you.
UPD: it seems you'll have to use reflection to inspect the actual type of the returned object.
Upvotes: 4