Callable インターフェース
開発者が共通インターフェースを使用して、異なるパッケージ内のコードでも Apex クラスまたはトリガー間の疎結合インテグレーションを作成できます。共通インターフェースについて合意することで、異なる会社や異なる部署の開発者が相互のソリューションに基づいてソリューションを作成できます。コミュニティの規模を拡大し、当初の予定とは異なるソリューションが必要になる場合、このインターフェースを実装してコードの機能を拡張します。
名前空間
使用方法
Callable インターフェースを実装するには、1 つのメソッド call(String action, Map<String, Object> args) のみを記述する必要があります。
Callable の実装を利用またはテストするコードで、該当する型のインスタンスを Callable にキャストします。
このインターフェースは、より具体的なインターフェースの定義の代わりになるものではありません。むしろ、Callable インターフェースは、異なるクラスやパッケージのコードで共通の基本型を使用できるインテグレーションを可能にするものです。
Callable の実装例
このクラスは、System.Callable インターフェースの実装例です。
1public class Extension implements Callable {
2
3 // Actual method
4 String concatStrings(String stringValue) {
5 return stringValue + stringValue;
6 }
7
8 // Actual method
9 Decimal multiplyNumbers(Decimal decimalValue) {
10 return decimalValue * decimalValue;
11 }
12
13 // Dispatch actual methods
14 public Object call(String action, Map<String, Object> args) {
15 switch on action {
16 when 'concatStrings' {
17 return this.concatStrings((String)args.get('stringValue'));
18 }
19 when 'multiplyNumbers' {
20 return this.multiplyNumbers((Decimal)args.get('decimalValue'));
21 }
22 when else {
23 throw new ExtensionMalformedCallException('Method not implemented');
24 }
25 }
26 }
27
28 public class ExtensionMalformedCallException extends Exception {}
29}次のテストコードは、コール元のコードがどのようにインターフェースを使用してメソッドをコールしているかを示しています。
1@IsTest
2private with sharing class ExtensionCaller {
3
4 @IsTest
5 private static void givenConfiguredExtensionWhenCalledThenValidResult() {
6
7 // Given
8 String extensionClass = 'Extension'; // Typically set via configuration
9 Decimal decimalTestValue = 10;
10
11 // When
12 Callable extension =
13 (Callable) Type.forName(extensionClass).newInstance();
14 Decimal result = (Decimal)
15 extension.call('multiplyNumbers', new Map<String, Object> {
16 'decimalValue' => decimalTestValue
17 });
18
19 // Then
20 System.assertEquals(100, result);
21 }
22}