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

クラスとキャスト

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

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

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

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

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

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

ヒント