类的实例称为对象。 就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创建
如您所知,sObjects是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);
静态变量使用
当类加载时静态变量只会被实例化一次,这种现象可以用来避免触发递归。 静态变量值将在相同的执行上下文中相同,并且正在执行的任何类,触发器或代码可以引用它并防止递归。