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));
...