0

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));
...
rcell
  • 661
  • 1
  • 9
  • 17

1 Answers1

4

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.

eugene-nikolaev
  • 1,230
  • 1
  • 12
  • 21
  • How does erasure work in this case? I thought `return (T)map.get(k)` would be type erased to `return (Float)map.get(k)` given that it can infer from the return value. – rcell Nov 15 '17 at 23:12
  • 1
    This answer contains a link to a pretty good article: https://stackoverflow.com/a/4590006/3323777 There is a workaround to keep the type information. Not sure if it is suitable in your case, please look. And the answer itself explains the erasure very well. – eugene-nikolaev Nov 15 '17 at 23:17