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

クラスとキャスト

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

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

1public virtual class Report {
2}
1public class CustomReport extends Report {
2}

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

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

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

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

ヒント