有人可以解释“ClassCastException”在Java? [英] Can someone explain "ClassCastException" in Java?

查看:163
本文介绍了有人可以解释“ClassCastException”在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一些关于ClassCastException的文章,但我不能得到一个好主意。

I read some articles written on "ClassCastException" but I couldn't get a good idea on that. Can someone direct me to a good article or explain it briefly.

推荐答案

直接从API规范 ClassCastException

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.

因此,例如,当试图投射 Integer 字符串 String 不是 Integer ,因此将抛出 ClassCastException

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.

这篇关于有人可以解释“ClassCastException”在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆