1. Introduction
1.绪论
ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It’s thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.
ClassCastException是Java中的一个运行时异常,当我们试图不正确地将一个类从一种类型投递到另一种类型时,它被抛出以表明代码试图将一个对象投递到一个相关的类,但它并不是一个实例。
For a more in-depth introduction to exceptions in Java, take a look here.
要想更深入地了解Java中的异常,请看看这里。
2. ClassCastException Details
2.ClassCastException详情
First, let’s take a look at a simple example. Consider the following code snippet:
首先,让我们看看一个简单的例子。考虑一下下面的代码片断。
String[] strArray = new String[] { "John", "Snow" };
ArrayList<String> strList = (ArrayList<String>) Arrays.asList(strArray);
System.out.println("String list: " + strList);
The above code causes ClassCastException where we cast the return value of Arrays.asList(strArray) to an ArrayList.
上面的代码导致了ClassCastException,我们将Arrays.asList(strArray)的返回值投给了ArrayList。
The reason is that although the static method Arrays.asList() returns a List, we don’t know until runtime exactly what implementation is returned. So at compile time the compiler can’t know either and allows the cast.
原因是,尽管静态方法Arrays.asList()返回一个List,我们在运行时才知道到底返回什么实现。所以在编译时,编译器也不能知道,并允许投掷.。
When the code runs, the actual implementation is checked which finds that Arrays.asList() returns an Arrays$List thus causing a ClassCastException.
当代码运行时,实际的实现被检查,发现Arrays.asList()返回一个Arrays$List,从而导致一个ClassCastException。
3. Resolution
3.决议
We can simply declare our ArrayList as a List to avoid this exception:
我们可以简单地将我们的ArrayList声明为List来避免这个异常。
List<String> strList = Arrays.asList(strArray);
System.out.println("String list: " + strList);
However, by declaring our reference as a List we can assign any class that implements the List interface, including the Arrays$ArrayList returned by the method call.
然而,通过将我们的引用声明为List,我们可以指定任何实现List接口的类,包括由方法调用返回的Arrays$ArrayList。
4. Summary
4.摘要
In this article, we’ve seen the explanation of what exactly is a ClassCastException and what measures we have to take this fix this issue.
在这篇文章中,我们已经看到了对到底什么是ClassCastException的解释,以及我们要采取什么措施来解决这个问题。
The full code can be found over on GitHub.
完整的代码可以在GitHub上找到over。