Apex-objects

提供:Dev Guides
移動先:案内検索

Apex-オブジェクト

クラスのインスタンスはオブジェクトと呼ばれます。 Salesforceの観点では、オブジェクトはクラスにすることも、sObjectのオブジェクトを作成することもできます。

クラスからのオブジェクト作成

Javaまたは他のオブジェクト指向プログラミング言語で行ったように、クラスのオブジェクトを作成できます。

以下はMyClassと呼ばれるクラスの例です-

//Sample Class Example
public class MyClass {
   Integer myInteger = 10;

   public void myMethod (Integer multiplier) {
      Integer multiplicationResult;
      multiplicationResult = multiplier*myInteger;
      System.debug('Multiplication is '+multiplicationResult);
   }
}

これはインスタンスクラスです。つまり、このクラスの変数またはメソッドを呼び出したりアクセスしたりするには、このクラスのインスタンスを作成する必要があります。その後、すべての操作を実行できます。

//Object Creation
//Creating an object of class
MyClass objClass = new MyClass();

//Calling Class method using Class instance
objClass.myMethod(100);

オブジェクトの作成

sObjectは、データを保存するSalesforceのオブジェクトです。 たとえば、アカウント、連絡先などはカスタムオブジェクトです。 これらのsObjectのオブジェクトインスタンスを作成できます。

以下はsObjectの初期化の例であり、ドット表記を使用して特定のオブジェクトのフィールドにアクセスし、フィールドに値を割り当てる方法を示しています。

//Execute the below code in Developer console by simply pasting it
//Standard Object Initialization for Account sObject
Account objAccount = new Account();//Object initialization
objAccount.Name = 'Testr Account';//Assigning the value to field Name of Account
objAccount.Description = 'Test Account';
insert objAccount;//Creating record using DML
System.debug('Records Has been created '+objAccount);

//Custom sObject initialization and assignment of values to field
APEX_Customer_c objCustomer = new APEX_Customer_c ();
objCustomer.Name = 'ABC Customer';
objCustomer.APEX_Customer_Decscription_c = 'Test Description';
insert objCustomer;
System.debug('Records Has been created '+objCustomer);

静的初期化

静的メソッドと変数は、クラスがロードされるときに一度だけ初期化されます。 静的変数は、Visualforceページのビューステートの一部として送信されません。

以下は、静的メソッドと静的変数の例です。

//Sample Class Example with Static Method
public class MyStaticClass {
   Static Integer myInteger = 10;

   public static void myMethod (Integer multiplier) {
      Integer multiplicationResult;
      multiplicationResult = multiplier * myInteger;
      System.debug('Multiplication is '+multiplicationResult);
   }
}

//Calling the Class Method using Class Name and not using the instance object
MyStaticClass.myMethod(100);

静的変数の使用

静的変数は、クラスがロードされたときに1回だけインスタンス化され、この現象を使用してトリガーの再帰を回避できます。 静的変数の値は同じ実行コンテキスト内で同じになり、実行中のクラス、トリガー、またはコードはそれを参照して再帰を防ぐことができます。