この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

クラスとキャスト

通常、すべての型情報は実行時に利用できます。つまり、Apex はキャストを許可しています。キャストとは、あるクラスのデータ型を別のクラスのデータ型として割り当てることです。ただし、割り当てるクラスが元のクラスの子である場合に限ります。あるデータ型のオブジェクトを別のデータ型に変換する場合にキャストを使用します。

次の例では、CustomReportReport クラスを拡張しています。そのため、そのクラスの子となっています。つまり、親のデータ型 (Report) のオブジェクトを、子のデータ型 (CustomReport) のオブジェクトにキャストできます。

次のコードブロックでは、まずレポートオブジェクトのリストにカスタムレポートオブジェクトが追加されます。その後、カスタムレポートオブジェクトがレポートオブジェクトとして返され、カスタムレポートオブジェクトとして再度キャストされます。

1Public virtual class Report {
2
3   Public class CustomReport extends Report {
4   // Create a list of report objects
5      Report[] Reports = new Report[5];
6
7   // Create a custom report object
8      CustomReport a = new CustomReport();
9
10   // Because the custom report is a sub class of the Report class,
11   // you can add the custom report object a to the list of report objects
12      Reports.add(a);
13
14   // The following is not legal, because the compiler does not know that what you are 
15   // returning is a custom report. You must use cast to tell it that you know what
16   // type you are returning
17   // CustomReport c = Reports.get(0);
18
19   // Instead, get the first item in the list by casting it back to a custom report object
20      CustomReport c = (CustomReport) Reports.get(0);
21   }
22}
キャストの例 Apex キャストプロセスのフローチャート

さらに、インターフェース型は、サブインターフェースまたはそのインターフェースを実装しているクラス型にキャストできます。

あるクラスが特定の型のクラスであることを確認するには、instanceOf キーワードを使用します。詳細は、instanceof キーワードの使用」を参照してください。

ヒント