Casting to generic type in Java doesn't raise ClassCastException?

后端 未结 5 1397
别跟我提以往
别跟我提以往 2020-11-28 15:46

I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastExcepti

5条回答
  •  余生分开走
    2020-11-28 16:15

    Java generics use type erasure, meaning those parameterized types aren't retained at runtime so this is perfectly legal:

    List list = new ArrayList();
    list.put("abcd");
    List list2 = (List)list;
    list2.add(3);
    

    because the compiled bytecode looks more like this:

    List list = new ArrayList();
    list.put("abcd");
    List list2 = list;
    list2.add(3); // auto-boxed to new Integer(3)
    

    Java generics are simply syntactic sugar on casting Objects.

提交回复
热议问题