Professional Documents
Culture Documents
Important Reserved Words: Keyword Description Example
Important Reserved Words: Keyword Description Example
Important Reserved Words: Keyword Description Example
try {
Important Reserved Words finally Identifies a block of
code that is guaranteed // Your code here
to execute } catch (ListException e) {
// List Exception handling code
Keyword Description Example } finally {
// will execute with or without
abstract Declares a class public abstract class Foo { // exception
that contains abstract protected void method1() { /*… */ } }
methods that only have abstract Integer abstractMethod();
} for (Integer i = 0, j = 0; i < 10;
their signature and no for Defines a loop. The
body defined. Can also three types of for loops i++) { System.debug(i+1);
define methods. are: iteration using a }
variable, iteration over
Integer[] myInts = new Integer[]{1,
break Exits the entire loop while(reader.hasNext()) { a list, and iteration over 8, 9};
if (reader.getEventType() == END) { a query for (Integer i : myInts) {
break; System.debug(i);
}; }
// process
reader.next(); String s = 'Acme';
} for (Account a : [SELECT Id, Name,
FROM account
catch Identifies a block of try { WHERE Name LIKE :(s+'%')]) {
code that can handle // Your code here // Your code
a particular type of }
} catch (ListException e) {
exception // List Exception handling code here
global Defines a class, global class myClass {
}
method, or variable webService static void
that can be used by any makeContact(String lastName) {
class Defines a class private class Foo { // do some work
private Integer x; Apex that has access
}
public Integer getX() { return x; } to the class, not just
} the Apex in the same
application.
continue Skips to the next while (checkBoolean) {
iteration of the loop if (condition) Integer i = 1;
if Defines a condition,
{continue; } if (i > 0) {
// do some work used to determine
whether a code block // do something;
} }
should be executed
do Defines a do-while Integer count = 1;
loop that executes do { implements Declares a class global class CreateTaskEmailExample
System.debug(count); or interface that implements Messaging.
repeatedly while a
count++; implements an InboundEmailHandler {
Boolean condition } while (count < 11); global Messaging.InboundEmailResult
remains true interface
handleInboundEmail(Messaging.
inboundEmail email,
else Defines the else Integer x, sign; Messaging.InboundEnvelope env){
portion of an if-else if (x==0) { // do some work, return value;
statement, that sign = 0; }
} else {
executes if the initial sign = 1;
evaluation is untrue }
}
instanceOf Verifies at runtime if (reports.get(0) instanceof
enum Defines an public enum Season {WINTER, SPRING, CustomReport) {
SUMMER, FALL}; whether an object is
enumeration type on actually an instance of // Can safely cast
a finite set of values Season e = Season.WINTER; CustomReport c = (CustomReport)
a particular class
reports.get(0);
extends Defines a class or public class MyException extends } else {
interface that extends Exception {} // Do something with the non-
custom-report.
another class or
try { }
interface
Integer i;
if (i < 5) throw new MyException(); interface Defines a data public interface PO {
} catch (MyException e) { public void doWork();
type with
// Your MyException handling code }
} method signatures.
public class MyPO implements PO {
Classes implement
public override doWork() {
Boolean isNotTrue = false; interfaces. An interface // actual implementation
false Identifies an untrue
can extend another }
value assigned to a
interface. }
Boolean
http://developer.salesforce.com
Important Reserved Words Important Reserved Words
Keyword Description Example Keyword Description Example
new Creates a new object, Foo f = new Foo(); trigger myAccountTrigger on Account
MyObject__c mo =
trigger Defines a trigger on an
sObject, or collection sObject (before insert, before update) {
instance new MyObject__c(Name= 'hello'); if (Trigger.isBefore) {
List<Account> la = new for (Account a : Trigger.old) {
List<Account>();
if (a.Name != 'okToDelete') {
null Identifies a null constant Boolean b = null; a.addError(
that can be assigned to any 'You can\'t delete this record!');
variable }
}
override Defines a method or public virtual class V { }
property as overriding public virtual void foo()
another defined as virtual {/*Does nothing*/}
} true Identifies a true value Boolean mustIterate = true;
in a class being extended assigned to a Boolean
or implemented public class RealV implements V {
public override void foo() { try {
// Do something real
try Identifies a block of code
in which an exception // Your code here
}
} can occur
} catch (ListException e) {
// List Exception handling code
private Defines a class, method, or public class OuterClass { // here
variable that is only known // Only visible to methods and }
locally, within the section // statements within OuterClass
private static final Integer
of code in which it is webService Defines a static method global class MyWebService {
MY_INT;
defined. This is the default } that is exposed as a webService static Id makeContact(
scope for all methods and Web service method that String lastName, Account a) {
variables that do not have can be called by external
a scope defined Contact c = new Contact(
client applications. LastName = 'Weissman',
protected Defines a method or public class Foo { Web service methods AccountId = a.Id);
variable that is visible to public void quiteVisible(); can only be defined in insert c;
any inner classes in the protected void lessVisible(); a global class. return c.Id;
} }
defining Apex class
}
public Defines a method or public class Foo {
variable that can be public void quiteVisible();
private void almostInvisible(); while Executes a block of Integer count=1;
used by any Apex in this while (count < 11) {
} code repeatedly as long
application or namespace System.debug(count);
as a particular Boolean
return Returns a value from a public Integer meaningOfLife() { count++;
condition remains true
return 42; }
method
}
public class OuterClass { with Enforces sharing rules that public with sharing class
static Defines a method or sharingClass {
variable that is only // Associated with instance sharing apply to the current user.
public static final Integer If absent, code is run under // Code will enforce current user's
initialized once, and is // sharing rules
MY_INT; default system context.
associated with an (outer) }
class, and initialization // Initialization code
code static { without Ensures that the sharing public without sharing class
MY_INT = 10; noSharing {
sharing rules of the current user
} // Code won't enforce current
} are not enforced
user's
public class AnotherChildClass // sharing rules
super Invokes a constructor on a }
superclass extends InnerClass {
AnotherChildClass(String s) {
super(); virtual Defines a class or method public virtual class MyException
// different constructor, no that allows extension extends Exception {
// args // Exception class member
}
and overrides. You can’t
// variable
} override a method
public Double d;
with the override
testmethod Defines a method as a static testmethod void testFoo() { keyword unless the class or
// some test logic // Exception class constructor
unit test method has been defined MyException(Double d) {
}
as virtual. this.d = d;
this Represents the current public class Foo { }
instance of a class, or in public Foo(String s) { /* … */}
constructor chaining public foo() { // Exception class method
this('memes repeat'); } protected void doIt() {}
} }
Primitive Types isDelete Returns true if this trigger was fired due to a delete operation
isBefore Returns true if this trigger was fired before any record was saved
Type Description Example
isAfter Returns true if this trigger was fired after all records were saved
Blob Binary data stored as a single Blob myBlob =
object Blob.valueof('idea'); isUndelete Returns true if this trigger was fired after a record is recovered from
the Recycle Bin
Boolean Value that can only be assigned Boolean isWinner = true;
true, false, or null new Returns a list of the new versions of the sObject records. (Only in
insert and update triggers, and the records can only be modified in
Date Particular day Date myDate = Date.today(); before triggers.)
Date weekStart =
myDate.toStartofWeek(); newMap A map of IDs to the new versions of the sObject records. (Only available in
Datetime Particular day and time Datetime myDateTime = before update, after insert, and after update triggers.)
Datetime.now();
old Returns a list of the old versions of the sObject records.
Datetime newd =
myDateTime. addMonths(2); (Only available in update and delete triggers.)
Trigger Context Variables Standard Classes and Methods (Subset)
System
Variable Operators abortJob assert assertEquals
assertNotEquals currentPageReference currentTimeMillis
oldMap A map of IDs to the old versions of the sObject records. debug isRunningTest now
(Only available in update and delete triggers.) process resetPassword runAs
schedule setPassword submit today
size The total number of records in a trigger invocation, both old and new. Math
abs acos asin atan atan2 cbrt ceil
Apex Data Manipulation Language (DML) Operations cos cosh exp floor log log10 max
min mod pow random rint round roundToLong
signum sin sinh sqrt tan tanh
Keyword Description Example
Describe
insert Adds one or Lead l = new Lead(Company='ABC', fields fieldSets getChildRelationships
more records LastName='Smith'); getKeyPrefix getLabel getLabelPlural
insert l;
getLocalName getName getRecordTypeInfos
delete Deletes one or Account[] doomedAccts = [SELECT Id, Name getRecordTypeInfosByID getSobjectType
more records FROM Account WHERE Name = 'DotCom']; isAccessible getRecordTypeInfosByName
try {
delete doomedAccts; isCreateable isCustom isCustomSetting
} catch (DmlException e) { isDeletable isDeprecatedAndHidden isFeedEnabled
// Process exception here isMergeable isQueryable isSearchable
} isUndeletable isUpdateable
merge Merges up to List<Account> ls = new List<Account>{ Schema.RecordTypeInfo rtByName = rtMapByName.get(rt.name);
three records of new Account(Name='Acme Inc.'), Schema.DescribeSObjectResult d = Schema.SObjectType.Account;
the same type new Account(Name='Acme')};
insert ls; DescribeFieldResult
into one of the
Account masterAcct = [SELECT Id, Name getByteLength getCalculatedFormula getController
records, deleting FROM Account WHERE Name = 'Acme Inc.'
the others, and getDefaultValue getDefaultValueFormula getDigits
LIMIT 1];
re-parenting any Account mergeAcct = [SELECT Id, Name FROM getInlineHelpText getLabel getLength
related records Account WHERE Name = 'Acme' LIMIT 1]; getLocalName getName getPicklistValues
try { merge masterAcct mergeAcct; getPrecision getReferenceTo getRelationshipName
} catch (DmlException e) { getRelationshipOrder getScale getSOAPType
} getSObjectField getType isAccessible
isAutoNumber isCalculated isCaseSensitive
undelete Restores one or Account[] savedAccts = [SELECT Id, Name isCreateable isCustom isDefaultedOnCreate
more records from FROM Account WHERE Name = 'Trump' isDependantPicklist isDeprecatedAndHidden isExternalID
the Recycle Bin ALL ROWS]; isFilterable isGroupable isHtmlFormatted
try { undelete savedAccts;
} catch (DmlException e) { isIdLookup isNameField isNamePointing
} isNillable isPermissionable isRestrictedDelete
isRestrictedPicklist isSortable isUnique
update Modifies one or Account a = new Account(Name='Acme2');
insert(a); isUpdateable isWriteRequiresMasterRead
more existing Schema.DescribeFieldResult f = Schema.SObjectType.Account.fields.Name;
records Account myAcct = [SELECT Id, Name,
BillingCity FROM Account WHERE Name
= 'Acme2' LIMIT 1]; LoggingLevel
myAcct.BillingCity = 'San Francisco'; ERROR WARN INFO DEBUG FINE FINER FINEST
try {
update myAcct; getAggregateQueries getLimitAggregateQueries
} catch (DmlException e) { getCallouts getLimitCallouts
} getChildRelationshipsDescribes getDMLRows
upsert Creates new Account[] acctsList = [SELECT Id, Name, getLimitChildRelationshipsDescribes getLimitDMLRows
records and BillingCity FROM Account WHERE getCPUTime getLimitCPUTime
updates existing BillingCity = 'Bombay']; getDMLRows getLimitDMLRows
for (Account a : acctsList) getDMLStatements getLimitDMLStatements
records
{a.BillingCity = 'Mumbai';}
Account newAcct = new Account( getEmailInvocations getLimitEmailInvocations
Name = 'Acme', BillingCity = getFieldsDescribes getLimitFieldsDescribes
'San Francisco'); getFindSimilarCalls getLimitFindSimilarCalls
acctsList.add(newAcct); getFutureCalls getLimitFutureCalls
try { upsert acctsList; getHeapSize getLimitHeapSize
} catch (DmlException e) { getPicklistDescribes getLimitPicklistDescribes
}
getQueries getLimitQueries
getQueryLocatorRows getLimitQueryLocatorRows
Standard Interfaces (Subset) getQueryRows getLimitQueryRows
getRecordTypesDescribes getLimitRecordTypesDescribes
Database.Batchable getRunAs getLimitRunAs
global (Database.QueryLocator | Iterable<sObject>) getSavepointRollbacks getLimitSavepointRollbacks
start(Database.BatchableContext bc) {}
getSavepoints getLimitSavepoints
global void execute(Database.BatchableContext BC, list<P>){}
global void finish(Database.BatchableContext BC){} getScriptStatements getLimitScriptStatements
getSoslQueries getLimitSoslQueries
Schedulable
global void execute(ScheduleableContext SC) {} UserInfo
getDefaultCurrency getFirstName getLanguage
Messaging.InboundEmailHandler getLastName getLocale getName
global Messaging.InboundEmailResult handleInboundEmail(Messaging. getOrganizationId getOrganizationName getProfileId
inboundEmail email, Messaging.InboundEnvelope env){} getSessionId getUITheme getUIThemeDisplayed
IsMultiCurrencyOrganization
Comparable String result = UserInfo.getLocale();
global Integer compareTo(Object compareTo) {} System.assertEquals('en_US', result);