Explanation of “ClassCastException” in Java

前端 未结 12 1661
小蘑菇
小蘑菇 2020-11-21 11:12

I read some articles written on \"ClassCastException\", but I couldn\'t get a good idea on that. Is there a good article or what would be a brief explanation?

12条回答
  •  迷失自我
    2020-11-21 11:46

    Straight from the API Specifications for the ClassCastException:

    Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

    So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.

    Object i = Integer.valueOf(42);
    String s = (String)i;            // ClassCastException thrown here.
    

提交回复
热议问题