Newer Version Available
カスタムイテレータ
イテレータは、コレクション内のすべての項目を辿ります。たとえば、Apex の while ループで、ループを終了する条件を定義し、コレクションを辿るいくつかの方法、つまりイテレータを提供する必要があります。次の例では、ループが実行されるごとに (count++)、count が 1 ずつ増加します。
1while (count < 11) {
2 System.debug(count);
3 count++;
4 }Iterator インターフェースを使用して、ループ全体のリストを辿るためのカスタムの一連の指示を作成できます。通常、SELECT ステートメントを使用して範囲を定義する Salesforce 外のソースにあるデータに役立ちます。複数の SELECT ステートメントがある場合にもイテレータを使用できます。
カスタムイテレータの使用
カスタムイテレータを使用するには、Iterator インターフェースを実装する Apex クラスを作成する必要があります。
Iterator クラスには次のインスタンスメソッドがあります。
| 名前 | 引数 | 戻り値 | 説明 |
|---|---|---|---|
| hasNext | Boolean | コレクション内の別の項目が辿られている場合は true が返され、そうでない場合は false が返されます。 | |
| next | anyType | コレクション内の次の項目を返します。 |
Iterator インターフェース内のすべてのメソッドは global または public として宣言する必要があります。
カスタムイテレータは while ループでのみ使用できます。次に例を示します。
イテレータは現在、for ループではサポートされていません。
1IterableString x = new IterableString('This is a really cool test.');
2
3 while(x.hasNext()){
4 system.debug(x.next());
5 }Iterable とカスタムイテレータの使用
リストでカスタムイテレータを使用せずに独自のデータ構造を作成する場合、Iterable インターフェースを使用してデータ構造を生成できます。
Iterable インターフェースには次のメソッドがあります。
| 名前 | 引数 | 戻り値 | 説明 |
|---|---|---|---|
| iterator | Iterator クラス | このインターフェースのイテレータへの参照を返します。 |
iterator メソッドは global または public として宣言する必要があります。データ構造の走査に使用できるイテレータへの参照を作成します。
次の例では、コレクションのカスタムイテレータの例を示します。
1swfobject.registerObject("clippy.codeblock-2", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17global class CustomIterable
18 implements Iterator<Account>{
19
20 List<Account> accs {get; set;}
21 Integer i {get; set;}
22
23 public CustomIterable(){
24 accs =
25 [SELECT Id, Name,
26 NumberOfEmployees
27 FROM Account
28 WHERE Name = 'false'];
29 i = 0;
30 }
31
32 global boolean hasNext(){
33 if(i >= accs.size()) {
34 return false;
35 } else {
36 return true;
37 }
38 }
39
40 global Account next(){
41 // 8 is an arbitrary
42 // constant in this example
43 // that represents the
44 // maximum size of the list.
45 if(i == 8){return null;}
46 i++;
47 return accs[i-1];
48 }
49}次で、上記のコードをコールします。
1swfobject.registerObject("clippy.codeblock-3", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17global class foo implements iterable<Account>{
18 global Iterator<Account> Iterator(){
19 return new CustomIterable();
20 }
21}
22次は、イテレータを使用する一括処理ジョブです。
1swfobject.registerObject("clippy.codeblock-4", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17global class batchClass implements Database.batchable<Account>{
18 global Iterable<Account> start(Database.batchableContext info){
19 return new foo();
20 }
21 global void execute(Database.batchableContext info, List<Account> scope){
22 List<Account> accsToUpdate = new List<Account>();
23 for(Account a : scope){
24 a.Name = 'true';
25 a.NumberOfEmployees = 69;
26 accsToUpdate.add(a);
27 }
28 update accsToUpdate;
29 }
30 global void finish(Database.batchableContext info){
31 }
32}