Java中ClassCastException的解释
我读了一些关于“ClassCastException”的文章,但我不太清楚它的含义。 什么是 ClassCastException?
I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
直接来自
ClassCastException 的 API 规范
:
因此,例如,当尝试将
Integer
转换为String
时,String
不是Integer
的子类>,因此将抛出ClassCastException
。Straight from the API Specifications for the
ClassCastException
:So, for example, when one tries to cast an
Integer
to aString
,String
is not an subclass ofInteger
, so aClassCastException
will be thrown.这真的非常简单:如果您尝试将 A 类的对象类型转换为 B 类的对象,并且它们不兼容,则会出现类转换异常。
让我们考虑一下类的集合。
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.
Let's think of a collection of classes.
如果您尝试向下转换一个类,但实际上该类不是该类型,则会发生异常。
考虑这个层次结构:
您可能有一个名为:
如果使用以下代码调用:
它将编译得很好,但在运行时您将得到一个 ClassCastException 因为 o 实际上是一个 Animal,而不是 Dog。
在 Java 的更高版本中,您确实会收到编译器警告,除非您这样做:
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:
You might have a method called:
If called with this code:
It will compile just fine, but at runtime you will get a
ClassCastException
because o was in fact an Animal, not a Dog.In later versions of Java you do get a compiler warning unless you do:
考虑一个示例,
在
Another t5 = (Another) new Goat()
处:您将收到ClassCastException
,因为您无法创建Another
的实例> 使用Goat
的类。注意:该转换仅在类扩展父类且子类强制转换为其父类的情况下有效。
如何处理 ClassCastException:
注释来源和其余的
Consider an example,
At
Another t5 = (Another) new Goat()
: you will get aClassCastException
because you cannot create an instance of theAnother
class usingGoat
.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
:Source of the Note and the Rest
你了解铸造的概念吗? 类型转换是类型转换的过程,这在 Java 中非常常见,因为它是一种静态类型语言。 一些示例:
通过
Integer.parseInt("1")
将字符串"1"
转换为int
-> 没问题将字符串
"abc"
转换为int
-> 引发ClassCastException
或者想象一个包含
Animal.class
、Dog.class
和Cat.class
的类图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:
Cast the String
"1"
to anint
, viaInteger.parseInt("1")
-> no problemCast the String
"abc"
to anint
-> raises aClassCastException
Or think of a class diagram with
Animal.class
,Dog.class
andCat.class
当您尝试将一种数据类型的对象转换为另一种数据类型时,Java 会引发类转换异常。
Java 允许我们将一种类型的变量转换为另一种类型,只要转换发生在兼容的数据类型之间。
例如,您可以将字符串转换为对象,类似地,包含字符串值的对象可以转换为字符串。
示例
假设我们有一个 HashMap,其中包含许多 ArrayList 对象。
如果我们编写这样的代码:
它会抛出类转换异常,因为哈希映射的 get 方法返回的值将是一个数组列表,但我们试图将其转换为字符串。 这会导致异常。
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
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.
您试图将对象视为类的实例,但它不是。 这大致类似于尝试按下吉他上的制音踏板(钢琴有制音踏板,吉他没有)。
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).
我可以为您提供 Java 中的 classcastException 的一个很好的例子,即使用“Collection”时,
上面的代码将在运行时为您提供 ClassCastException。 因为您试图将 Integer 转换为 String,所以会引发异常。
A very good example that I can give you for classcastException in Java is while using "Collection"
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
一旦您认识到 JVM 无法猜测未知数,您就可以更好地理解 ClassCastException 和转换。 如果 B 是 A 的实例,则它在堆上拥有比 A 更多的类成员和方法。由于映射目标较大,JVM 无法猜测如何将 A 转换为 B,并且 JVM 将不知道如何填充额外的成员。
但如果 A 是 B 的实例,则这是可能的,因为 A 是对 B 的完整实例的引用,因此映射将是一对一的。
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.
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.
Exception 不是 RuntimeException 的子类 -> 类转换异常
Exception is not a subclass of RuntimeException -> ClassCastException
Java ClassCastException 是当您尝试将类从一种类型不正确地转换为另一种类型时可能发生的异常。
如果您尝试运行这个 Java 程序,您将看到它将抛出以下 ClassCastException:
这里抛出异常的原因是,当我创建列表对象时,我存储在列表中的对象是字符串“one” ,”但后来当我尝试取出这个对象时,我故意犯了一个错误,试图将其转换为整数。 因为 String 不能直接转换为 Integer(Integer 不是 String 的类型),所以会引发 ClassCastException。
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
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.
如果你想对对象进行排序,但类没有实现 Comparable 或 Comparator,那么你将得到 ClassCastException
例如
上面的 main 方法将抛出下面的运行时类强制转换异常
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException
For example
Above main method will throw below runtime class cast exception