中級 › ClassCastException の原因と直し方 › パターン2
ClassCastException の原因と直し方
キャストは宣言にすぎず、実体が違えば実行時に落ちます。
1 public class Main { 2 public static void main(String[] args) { 3 Object o = "java"; 4 Integer n = (_______) o; ^ 5 System.out.println(n); 6 } 7 }
Exception in thread "main" java.lang.ClassCastException:
class java.lang.String cannot be cast to class java.lang.Integerexited with code 1
空欄を埋めてビルドを通す
キャストは「そう扱う」という宣言にすぎません。実体が違えば実行時に落ちます。instanceofで事前に確認します。
次の問題