Code Fix

中級ClassCastException の原因と直し方 › パターン1

ClassCastException の原因と直し方

キャストは宣言にすぎず、実体が違えば実行時に落ちます。

 1  public class Main {
 2      public static void main(String[] args) {
 3          Object o = "java";
 4          ________ s = (String) o;
                ^
 5          System.out.println(s);
 6      }
 7  }
Main.java:4: error: incompatible types: String cannot be converted to Integer

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

ClassCastException の原因と直し方

instanceofによる事前確認を扱います。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)