Java中“ClassCastException”的解释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/907360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explanation of "ClassCastException" in Java
提问by Chathuranga Chandrasekara
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?
我读了一些关于“ClassCastException”的文章,但我对此没有一个好主意。有没有好的文章或者什么是简短的解释?
采纳答案by coobird
Straight from the API Specifications for the ClassCastException
:
直接来自以下 API 规范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.
因此,例如,当尝试将 an 强制转换Integer
为 a 时String
, ,String
不是 的子类Integer
,因此ClassCastException
将抛出 a 。
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
回答by Charlie Martin
It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
这真的很简单:如果您尝试将 A 类对象类型转换为 B 类对象,并且它们不兼容,则会出现类转换异常。
Let's think of a collection of classes.
让我们考虑一个类的集合。
class A {...}
class B extends A {...}
class C extends A {...}
- You can cast any of these things to Object, because all Java classes inherit from Object.
- You can cast either B or C to A, because they're both "kinds of" A
- You can cast a reference to an A object to B only ifthe real object is a B.
- You can't cast a B to a C even though they're both A's.
- 您可以将这些东西中的任何一个转换为 Object,因为所有 Java 类都继承自 Object。
- 您可以将 B 或 C 转换为 A,因为它们都是 A 的“种类”
- 只有当真实对象是 B 时,您才能将 A 对象的引用转换为 B。
- 即使它们都是 A,您也不能将 B 转换为 C。
回答by Mork0075
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
你了解铸造的概念吗?强制转换是类型转换的过程,这在 Java 中很常见,因为它是一种静态类型语言。一些例子:
Cast the String "1" to an int -> no problem
将字符串“1”转换为 int -> 没问题
Cast the String "abc" to an int -> raises a ClassCastException
将字符串“abc”转换为 int -> 引发 ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
或者想想一个带有 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.
回答by Jeremy Huiskamp
You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).
您试图将一个对象视为它不是的类的实例。这大致类似于试图按下吉他上的制音踏板(钢琴有制音踏板,吉他没有)。
回答by Yishai
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
如果您尝试向下转换类,则会发生异常,但实际上该类不是该类型。
Consider this heirarchy:
考虑这个层次结构:
Object -> Animal -> Dog
对象 -> 动物 -> 狗
You might have a method called:
你可能有一个方法叫做:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
如果使用此代码调用:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException
because o was in fact an Animal, not a Dog.
它会编译得很好,但在运行时你会得到一个,ClassCastException
因为 o 实际上是一个动物,而不是狗。
In later versions of Java you do get a compiler warning unless you do:
在 Java 的更高版本中,除非您执行以下操作,否则您会收到编译器警告:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
回答by shakun tyagi
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
当您尝试将一种数据类型的 Object 转换为另一种数据类型时,Java 会抛出类转换异常。
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
只要转换发生在兼容的数据类型之间,Java 就允许我们将一种类型的变量转换为另一种类型。
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
例如,您可以将 String 转换为 Object,类似地,可以将包含 String 值的 Object 转换为 String。
Example
例子
Let us assume we have an HashMap that holds a number of ArrayList objects.
让我们假设我们有一个 HashMap,其中包含许多 ArrayList 对象。
If we write code like this:
如果我们写这样的代码:
String obj = (String) hmp.get(key);
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.
它会抛出一个类转换异常,因为哈希映射的 get 方法返回的值将是一个数组列表,但我们试图将它转换为一个字符串。这会导致异常。
回答by Mistriel
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
一旦您意识到 JVM 无法猜测未知数,您就可以更好地理解 ClassCastException 和强制转换。如果 B 是 A 的实例,它在堆上的类成员和方法比 A 多。由于映射目标更大,JVM 无法猜测如何将 A 强制转换为 B,并且 JVM 将不知道如何填充额外的成员。
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
但是如果 A 是 B 的一个实例,这是可能的,因为 A 是对 B 的完整实例的引用,所以映射将是一对一的。
回答by Elizabeth Courpalis
Consider an example,
考虑一个例子,
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();
}
}
At Another t5 = (Another) new Goat()
: you will get a ClassCastException
because you cannot create an instance of the Another
class using Goat
.
在Another t5 = (Another) new Goat()
:您将得到 ,ClassCastException
因为您无法Another
使用Goat
.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
注意:转换仅在类扩展父类并且子类被强制转换为其父类的情况下有效。
How to deal with the ClassCastException
:
如何处理ClassCastException
:
- Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
- You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.
- 尝试将一个类的对象转换为另一个类时要小心。确保新类型属于其父类之一。
- 您可以通过使用泛型来防止 ClassCastException,因为泛型提供编译时检查并可用于开发类型安全的应用程序。
回答by Suganthan Madhavan Pillai
A very good example that I can give you for classcastException in Java is while using "Collection"
我可以在 Java 中为 classcastException 提供的一个很好的例子是使用“Collection”
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
上面的代码将在运行时为您提供 ClassCastException。因为您试图将 Integer 转换为 String,所以会引发异常。
回答by Ananta Chandra Das
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
Java ClassCastException 是当您尝试将类从一种类型错误地转换为另一种类型时可能发生的异常。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
list.add("two");
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you'll see that it will throw the following ClassCastException:
如果您尝试运行此 Java 程序,您将看到它将抛出以下 ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main (ClassCastExceptionExample.java:19)
The reason an exception is thrown here is that when I'm creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.
这里抛出异常的原因是,当我创建我的列表对象时,我存储在列表中的对象是字符串“one”,但是后来当我试图把这个对象取出来时,我故意犯了一个错误将其转换为整数。因为 String 不能直接转换为 Integer — Integer 不是 String 的类型 — 会抛出 ClassCastException。