instanceof キーワードの使用
実行時に、オブジェクトが実際に特定のクラスのインスタンスであることを確認するには、instanceof キーワードを使用します。instanceof キーワードは、式中のキーワードの右にある対象の型を、キーワードの左で宣言される型の代替にできるかどうかを調べる場合のみに使用できます。
クラスとキャストの例の Report クラスで、項目を CustomReport オブジェクトに再度キャストする前に、次の確認を追加できます。
1If (Reports.get(0) instanceof CustomReport) {
2 // Can safely cast it back to a custom report object
3 CustomReport c = (CustomReport) Reports.get(0);
4 } Else {
5 // Do something with the non-custom-report.
6}