【Java踩坑记】——ClassCastException

问题:

先来看一段代码:

    public static void main(String[] args) {
        int i = 0 ;
        Object x = i;
        System.out.println((String) x);
    }

虽然再代码编译阶段,编译器并不会报任何异常,但是如果运行起来我们会发现会有如下错误:Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String。

描述:

从jdk文档中我们找到如下描述:

public class ClassCastException extends RuntimeException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

我们可以看到ClassCastException是一个运行时错误。导致该异常的原因是,我们将一个Object向下转型的时候指向了一个错误的类型。

由此可将,向下转型确实存在不安全因素。我们再使用向下转型的时候,一定要注意相关问题。

相关问题:

我们都知道int是基本数据类型。当把基本数据类型赋值给Objcet对象的时候会发生如下转换:

  1. 将基本数据类型int自动装箱为Integer对象。
  2. 将Integer对象向上转型为Objcet对象。

猜你喜欢

转载自blog.csdn.net/syy19940213/article/details/81349095