Cha*_*ara 71 java casting classcastexception
我读了一些关于"ClassCastException"的文章,但我无法对此有所了解.是否有一篇好文章或什么是简短的解释?
coo*_*ird 110
直接来自API规范ClassCastException:
抛出以指示代码已尝试将对象强制转换为不是实例的子类.
因此,例如,当一个人试图将a转换Integer为a时String,String不是它的子类Integer,因此ClassCastException将抛出一个.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
Run Code Online (Sandbox Code Playgroud)
Cha*_*tin 81
这非常简单:如果您试图将类A的对象类型转换为类B的对象,并且它们不兼容,则会出现类转换异常.
让我们想一下课程的集合.
class A {...}
class B extends A {...}
class C extends A {...}
Run Code Online (Sandbox Code Playgroud)
Yis*_*hai 20
如果您尝试向下转换类,则会发生异常,但实际上该类不属于该类.
考虑这个heirarchy:
对象 - >动物 - >狗
您可能有一个名为的方法:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
Run Code Online (Sandbox Code Playgroud)
如果使用此代码调用:
Animal a = new Animal();
manipulate(a);
Run Code Online (Sandbox Code Playgroud)
它会编译得很好,但在运行时你会得到一个ClassCastException因为o实际上是动物,而不是狗.
在Java的更高版本中,您会收到编译器警告,除非您执行以下操作:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
Run Code Online (Sandbox Code Playgroud)
小智 9
考虑一个例子,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
Run Code Online (Sandbox Code Playgroud)
在Another t5 = (Another) new Goat():您将获得一个ClassCastException因为您无法使用创建Another类的实例Goat.
注意:仅当类扩展父类并且子类已转换为其父类时,转换才有效.
如何应对ClassCastException:
你了解铸造的概念吗?转换是类型转换的过程,它在Java中很常见,因为它是一种静态类型语言.一些例子:
将字符串"1"转换为int - >没问题
将字符串"abc"转换为int - >引发ClassCastException
或者想一下使用Animal.class,Dog.class和Cat.class的类图
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.
Run Code Online (Sandbox Code Playgroud)