Sunteți pe pagina 1din 4

Apex Code Cheat Sheet App Logic

http://developer.force.com
Overview
Force.com Apex code is a strongly-typed programming language that executes on the
Force.com platform. Using Apex, you can add business logic to applications, write database
triggers, and program controllers used with Visualforce. Apex has a tight integration with
the database and query language, web service, and email handling support. It also includes
features such as asynchronous execution and support for testing.
Important Reserved Words
Keyword Description Example
abstract Declares a class that
contains abstract
methods that only have
their signature and no
body defined. Can also
define methods.
publ i c abstract cl ass Foo {
pr ot ect ed voi d met hod1( ) { / **/ }
abstract I nt eger abst r act Met hod( ) ;
}
break Exits the entire loop whi l e( r eader . hasNext ( ) ) {
i f ( r eader . get Event Type( ) == END) {
break;
};
/ / pr ocess
r eader . next ( ) ;
}
catch Identifies a block of
code that can handle
a particular type of
exception
t r y {
/ / Your code her e
} catch ( Li st Except i on e) {
/ / Li st Except i on handl i ng code her e
}
class Defines a class pr i vat e class Foo {
pr i vat e I nt eger x;
publ i c I nt eger get X( ) { r et ur n x; }
}
continue Skips to the next
iteration of the loop
whi l e ( checkBool ean) {
i f ( condi t i on)
{continue; }
/ / do some wor k
}
do Defines a do-while
loop that executes
repeatedly while a
Boolean condition
remains true
I nt eger count = 1;
do {
Syst em. debug( count ) ;
count ++;
} whi l e ( count < 11) ;
else Defines the else
portion of an if-else
statement, that
executes if the initial
evaluation is untrue
I nt eger x, si gn;
i f ( x==0) {
si gn = 0;
} else {
si gn = 1;
}
enum Defines an
enumeration type on a
finite set of values
publ i c enum Season {WI NTER, SPRI NG,
SUMMER, FALL};
Season e = Season. WI NTER;
extends Defines a class or
interface that extends
another class or
interface
publ i c cl ass MyExcept i on extends
Except i on {}
t r y {
I nt eger i ;
i f ( i < 5) t hr ow new MyExcept i on( ) ;
} cat ch ( MyExcept i on e) {
/ / Your MyExcept i on handl i ng code
}
false Identifies an untrue
value assigned to a
Boolean
Bool ean i sNot Tr ue = false;
Important Reserved Words
Keyword Description Example
final Defines constants and
methods that cant be
overridden
publ i c cl ass myCl s {
st at i c final I nt eger I NT_CONST;
}
finally Identifies a block
of code that is
guaranteed to execute
t r y {
/ / Your code her e
} cat ch ( Li st Except i on e) {
/ / Li st Except i on handl i ng code
} finally {
/ / wi l l execut e wi t h or wi t hout
/ / except i on
}
for Defines a loop. The
three types of for loops
are: iteration using a
variable, iteration over
a list, and iteration
over a query
for ( I nt eger i = 0, j = 0; i < 10;
i ++) { Syst em. debug( i +1) ;
}
I nt eger [ ] myI nt s = new I nt eger [ ] {1,
8, 9};
for ( I nt eger i : myI nt s) {
Syst em. debug( i ) ;
}
St r i ng s = ' Acme' ;
for ( Account a : [ SELECT I d, Name,
FROM account
WHERE Name LI KE : ( s+' %' ) ] ) {
/ / Your code
}
global Defines a class,
method, or variable
that can be used by
any Apex that has
access to the class,
not just the Apex in the
same application.
global cl ass myCl ass {
webSer vi ce st at i c voi d
makeCont act ( St r i ng l ast Name) {
/ / do some wor k
}
if Defines a condition,
used to determine
whether a code block
should be executed
I nt eger i = 1;
if ( i > 0) {
/ / do somet hi ng;
}
implements Declares a class
or interface that
implements an
interface
gl obal cl ass Cr eat eTaskEmai l Exampl e
implements Messagi ng.
I nboundEmai l Handl er {
gl obal Messagi ng. I nboundEmai l Resul t
handl eI nboundEmai l ( Messagi ng.
i nboundEmai l emai l ,
Messagi ng. I nboundEnvel ope env) {
/ / do some wor k, r et ur n val ue;
}
}
instanceOf Verifies at runtime
whether an object is
actually an instance of
a particular class
i f ( r epor t s. get ( 0) instanceof
Cust omRepor t ) {
/ / Can saf el y cast
Cust omRepor t c = ( Cust omRepor t )
r epor t s. get ( 0) ;
} el se {
/ / Do somet hi ng wi t h t he non-
cust om- r epor t .
}
interface Defines a data
type with method
signatures. Classes
implement interfaces.
An interface can
extend another
interface.
publ i c interface PO {
publ i c voi d doWor k( ) ;
}
publ i c cl ass MyPO i mpl ement s PO {
publ i c over r i de doWor k( ) {
/ / act ual i mpl ement at i on
}
}
Important Reserved Words
Keyword Description Example
new Creates a new object,
sObject, or collection
instance
Foo f = new Foo( ) ;
MyObj ect __c mo =
new MyObj ect __c( Name= ' hel l o' ) ;
Li st <Account > l a = new
Li st <Account >( ) ;
null Identifies a null constant
that can be assigned to
any variable
Bool ean b = null;
override Defines a method or
property as overriding
another defined as virtual
in a class being extended
or implemented
publ i c vi r t ual cl ass V {
publ i c vi r t ual voi d f oo( )
{/ *Does not hi ng*/ }
}
publ i c cl ass Real V i mpl ement s V {
publ i c override voi d f oo( ) {
/ / Do somet hi ng r eal
}
}
private Defines a class, method, or
variable that is only known
locally, within the section
of code in which it is
defined. This is the default
scope for all methods and
variables that do not have
a scope defined
publ i c cl ass Out er Cl ass {
/ / Onl y vi si bl e t o met hods and
/ / st at ement s wi t hi n Out er Cl ass
private st at i c f i nal I nt eger
MY_I NT;
}
protected Defines a method or
variable that is visible to
any inner classes in the
defining Apex class
publ i c cl ass Foo {
publ i c voi d qui t eVi si bl e( ) ;
protected voi d l essVi si bl e( ) ;
}
public Defines a method or
variable that can be
used by any Apex in this
application or namespace
public cl ass Foo {
public voi d qui t eVi si bl e( ) ;
pr i vat e voi d al most I nvi si bl e( ) ;
}
return Returns a value from a
method
publ i c I nt eger meani ngOf Li f e( ) {
return 42;
}
static Defines a method or
variable that is only
initialized once, and is
associated with an (outer)
class, and initialization
code
publ i c cl ass Out er Cl ass {
/ / Associ at ed wi t h i nst ance
publ i c static f i nal I nt eger
MY_I NT;
/ / I ni t i al i zat i on code
static {
MY_I NT = 10;
}
}
super Invokes a constructor on a
superclass
publ i c cl ass Anot her Chi l dCl ass
ext ends I nner Cl ass {
Anot her Chi l dCl ass( St r i ng s) {
super( ) ;
/ / di f f er ent const r uct or , no
/ / ar gs
}
}
testmethod Defines a method as a
unit test
st at i c testmethod voi d t est Foo( ) {
/ / some t est l ogi c
}
this Represents the current
instance of a class, or in
constructor chaining
publ i c cl ass Foo {
publ i c Foo( St r i ng s) { / * */ }
publ i c f oo( ) {
this( ' memes r epeat ' ) ; }
}
throw Throws an exception,
signaling that an error has
occurred
publ i c cl ass MyExcept i on ext ends
Except i on {}
t r y {
I nt eger i ;
i f ( i < 5)
throw new MyExcept i on( ) ;
} cat ch ( MyExcept i on e) {
/ / Your MyExcept i on handl i ng
/ / code her e
}
transient Declares instance
variables that cannot be
saved, and should not be
transmitted as part of the
view state, in Visualforce
controllers and extensions
transient i nt eger cur r ent Val ue;
Important Reserved Words
Keyword Description Example
trigger Defines a trigger on an
sObject
trigger myAccount Tr i gger on Account
( bef or e i nser t , bef or e updat e) {
i f ( Tr i gger . i sBef or e) {
f or ( Account a : Tr i gger . ol d) {

i f ( a. Name ! = ' okToDel et e' ) {
a. addEr r or (
' You can\ ' t del et e t hi s r ecor d! ' ) ;
}
}
}
true Identifies a true value
assigned to a Boolean
Bool ean must I t er at e = true;
try Identifies a block of
code in which an
exception can occur
try {
/ / Your code her e

} cat ch ( Li st Except i on e) {
/ / Li st Except i on handl i ng code
/ / her e
}
webService Defines a static
method that is
exposed as a Web
service method
that can be called
by external client
applications. Web
service methods can
only be defined in a
global class.
gl obal cl ass MyWebSer vi ce {
webService st at i c I d makeCont act (
St r i ng l ast Name, Account a) {
Cont act c = new Cont act (
Last Name = ' Wei ssman' ,
Account I d = a. I d) ;
i nser t c;
r et ur n c. I d;
}
}
while Executes a block of
code repeatedly as
long as a particular
Boolean condition
remains true
I nt eger count =1;
while ( count < 11) {
Syst em. debug( count ) ;
count ++;
}
with sharing Enforces sharing
rules that apply to
the current user.
If absent, code is run
under default system
context.
publ i c with sharing cl ass
shar i ngCl ass {
/ / Code wi l l enf or ce cur r ent user ' s
/ / shar i ng r ul es
}
without
sharing
Ensures that the
sharing rules of the
current user are not
enforced
publ i c without sharing cl ass
noShar i ng {
/ / Code won' t enf or ce cur r ent user ' s
/ / shar i ng r ul es
}
virtual Defines a class or
method that allows
extension and
overrides. You cant
override a method
with the over r i de
keyword unless the
class or method has
been defined as
vi r t ual .
publ i c virtual cl ass MyExcept i on
ext ends Except i on {
/ / Except i on cl ass member
/ / var i abl e
publ i c Doubl e d;
/ / Except i on cl ass const r uct or
MyExcept i on( Doubl e d) {
t hi s. d = d;
}

/ / Except i on cl ass met hod
pr ot ect ed voi d doI t ( ) {}
}
Annotations
Annotation Description Example
@future Denotes methods
that are executed
asynchronously
gl obal cl ass MyFut ur eCl ass {
@future
st at i c voi d myMet hod(
St r i ng a, I nt eger i ) {
Syst em. debug(
' Met hod cal l ed wi t h: ' + a +
' and ' + i ) ;
/ / do cal l out , ot her l ong
/ / r unni ng code
}
}
Annotations
Annotation Description Example
@isTest Denotes classes that only
contain code used for
testing your application.
These classes dont count
against the total amount
of Apex used by your
organization.
@isTest pr i vat e cl ass MyTest {
/ / Met hods f or t est i ng
}
@isTest(
OnInstall=true)
Denotes a test class or
test method that executes
on package installation
@isTest(OnInstall=true)
pr i vat e cl ass Test Cl ass {
}
@isTest(
SeeAllData=true)
Denotes a test class or
test method that has
access to all data in the
organization including pre-
existing data that the test
didn't create. The default
is false.
@isTest(SeeAllData=true)
pr i vat e cl ass Test Cl ass {
}
@deprecated Denotes methods, classes,
exceptions, enums,
interfaces, or variables
that can no longer be
referenced in subsequent
releases of the managed
package in which they
reside
@deprecated
publ i c voi d l i mi t edShel f Li f e( ) {
}
@readOnly Denotes methods that
can perform queries
unrestricted by the number
of returned rows limit for a
request
@readOnly
pr i vat e voi d doQuer y( ) {
}
@remoteAction Denotes Apex controller
methods that J avaScript
code can call from a
Visualforce page via
J avaScript remoting. The
method must be static and
either public or global.
@remoteAction
gl obal st at i c St r i ng get I d(
St r i ng s) {
}
@restResource Denotes a class that
is available as a REST
resource. The class must
be global. The urlMapping
parameter is your
resource's name and is
relative to https://instance.
salesforce.com/services/
apexrest/.
@restResource(urlMapping=
'/Widget/*')
gl obal wi t h shar i ng cl ass
MyResour ce( ) {
}
@httpGet,
@httpPost,
@httpPatch,
@httpPut,
@httpDelete
Denotes a REST method
in a class annotated with
@r est Resour ce that
the runtime invokes when
a client sends an HTTP
GET, POST, PATCH,
PUT, or DELETE
respectively.
The methods defined with
any of these annotations
must be global and static.
@httpGet
gl obal st at i c MyWi dget __c doGet ( )
{
}
@httpPost
gl obal st at i c voi d doPost ( ) {
}
@httpDelete
gl obal st at i c voi d doDel et e( ) {
}
Primitive Types
Type Description Example
Decimal Number that includes a decimal
point. Decimal is an arbitrary
precision number.
Decimal myDeci mal = 12. 4567;
Deci mal di vDec = myDeci mal .
di vi de
( 7, 2, Syst em. Roundi ngMode. UP) ;
syst em. asser t Equal s( di vDec,
1. 78) ;
Double 64-bit number that includes a
decimal point. Minimum value -2
63
.
Maximum value of 2
63
-1
Double d=3. 14159;
ID 18-character Force.com record
identifier
ID i d=' 00300000003T2PGAA0' ;
Integer 32-bit number that doesnt include
a decimal point. Minimum value
-2,147,483,648 -- maximum value
of 2,147,483,647
Integer i = 1;
Long 64-bit number that doesnt include
a decimal point. Minimum value of
-2
63
-- maximum value of 2
63
-1.
Long l = 2147483648L;
String Set of characters surrounded by
single quotes
String s = ' r epeat i ng memes' ;
Time Particular time Time myTi me =
Time. newI nst ance( 18, 30, 2,
20) ;
I nt eger myMi nut es = myTi me.
mi nut e( ) ;
Collection Types
List Ordered collection
of typed primitives,
sObjects, objects,
or collections that
are distinguished by
their indices
/ / Cr eat e an empt y l i st of St r i ng
List<St r i ng> my_l i st = new
List<St r i ng>( ) ;
My_l i st . add( ' hi ' ) ;
St r i ng x = my_l i st . get ( 0) ;
/ / Cr eat e l i st of r ecor ds f r oma quer y
List<Account > accs = [ SELECT I d, Name
FROM
Account LI MI T 1000] ;
Map Collection of key-
value pairs where
each unique key
maps to a single
value. Keys can be
any primitive data
type, while values
can be a primitive,
sObject, collection
type, or an object.
Map<St r i ng, St r i ng> mys = new Map<St r i ng,
St r i ng>( ) ;
Map<St r i ng, St r i ng> mys = new Map<St r i ng,
St r i ng>{' a' => ' b' , ' c' => ' d' .
t oUpper Case( ) };
Account myAcct = new Account ( ) ;
Map<I nt eger , Account > m= new
Map<I nt eger , Account >( ) ;
m. put ( 1, myAcct ) ;
Set Unordered collection
that doesnt contain
any duplicate
elements.
Set<I nt eger > s = new Set<I nt eger >( ) ;
s. add( 12) ;
s. add( 12) ;
Syst em. asser t ( s. si ze( ) ==1) ;
Trigger Context Variables
Variable Operators
i sExecut i ng Returns true if the current context for the Apex code is a trigger only
i sI nser t Returns true if this trigger was fired due to an insert operation
i sUpdat e Returns true if this trigger was fired due to an update operation
i sDel et e Returns true if this trigger was fired due to a delete operation
i sBef or e Returns true if this trigger was fired before any record was saved
i sAf t er Returns true if this trigger was fired after all records were saved
i sUndel et e Returns true if this trigger was fired after a record is recovered from the
Recycle Bin
new Returns a list of the new versions of the sObject records. (Only in i nser t
and updat e triggers, and the records can only be modified in bef or e
triggers.)
newMap A map of IDs to the new versions of the sObject records. (Only available
in bef or e updat e, af t er i nser t , and af t er updat e triggers.)
ol d Returns a list of the old versions of the sObject records. (Only available in
updat e and del et e triggers.)
Primitive Types
Type Description Example
Blob Binary data stored as a single
object
Blob myBl ob =
Blob. val ueof ( ' i dea' ) ;
Boolean Value that can only be assigned
true, false, or null
Boolean i sWi nner = t r ue;
Date Particular day Date myDat e = Dat e. t oday( ) ;
Date weekSt ar t =
myDat e. t oSt ar t of Week( ) ;
Datetime Particular day and time Datetime myDat eTi me =
Dat et i me. now( ) ;
Datetime newd =
myDat eTi me. addMont hs( 2) ;
Trigger Context Variables
Variable Operators
ol dMap A map of IDs to the old versions of the sObject records. (Only
available in updat e and del et e triggers.)
si ze The total number of records in a trigger invocation, both old and new.
Apex Data Manipulation Language (DML) Operations
Keyword Description Example
insert Adds one or
more records
Lead l = new Lead( Company=' ABC' ,
Last Name=' Smi t h' ) ;
insert l ;
delete Deletes one or
more records
Account [ ] doomedAcct s = [ SELECT I d, Name
FROM Account WHERE Name = ' Dot Com' ] ;
t r y {
delete doomedAcct s;
} cat ch ( Dml Except i on e) {
/ / Pr ocess except i on her e
}
merge Merges up to
three records of
the same type
into one of the
records, deleting
the others, and
re-parenting any
related records
Li st <Account > l s = new Li st <Account >{
new Account ( Name=' Acme I nc. ' ) ,
new Account ( Name=' Acme' ) };
i nser t l s;
Account mast er Acct = [ SELECT I d, Name
FROM Account WHERE Name = ' Acme I nc. '
LI MI T 1] ;
Account mer geAcct = [ SELECT I d, Name FROM
Account WHERE Name = ' Acme' LI MI T 1] ;
t r y { merge mast er Acct mer geAcct ;
} cat ch ( Dml Except i on e) {
}
undelete Restores one
or more records
from the Recycle
Bin
Account [ ] savedAcct s = [ SELECT I d, Name
FROM Account WHERE Name = ' Tr ump'
ALL ROWS] ;
t r y { undelete savedAcct s;
} cat ch ( Dml Except i on e) {
}
update Modifies one or
more existing
records
Account a = new Account ( Name=' Acme2' ) ;
i nser t ( a) ;
Account myAcct = [ SELECT I d, Name,
Bi l l i ngCi t y FROM Account WHERE Name
= ' Acme2' LI MI T 1] ;
myAcct . Bi l l i ngCi t y = ' San Fr anci sco' ;
t r y {
update myAcct ;
} cat ch ( Dml Except i on e) {
}
upsert Creates new
records and
updates existing
records
Account [ ] acct sLi st = [ SELECT I d, Name,
Bi l l i ngCi t y FROM Account WHERE
Bi l l i ngCi t y = ' Bombay' ] ;
f or ( Account a : acct sLi st )
{a. Bi l l i ngCi t y = ' Mumbai ' ; }
Account newAcct = new Account (
Name = ' Acme' , Bi l l i ngCi t y =
' San Fr anci sco' ) ;
acct sLi st . add( newAcct ) ;
t r y { upsert acct sLi st ;
} cat ch ( Dml Except i on e) {
}
Standard Interfaces (Subset)
Database.Batchable
gl obal ( Dat abase. Quer yLocat or | I t er abl e<sObj ect >)
st ar t ( Dat abase. Bat chabl eCont ext bc) {}
gl obal voi d execut e( Dat abase. Bat chabl eCont ext BC, l i st <P>) {}
gl obal voi d f i ni sh( Dat abase. Bat chabl eCont ext BC) {}
Schedulable
gl obal voi d execut e( Schedul eabl eCont ext SC) {}
Messaging.InboundEmailHandler
gl obal Messagi ng. I nboundEmai l Resul t handl eI nboundEmai l ( Messagi ng.
i nboundEmai l emai l , Messagi ng. I nboundEnvel ope env) {}
Comparable
gl obal I nt eger compar eTo( Obj ect compar eTo) {}
For other cheatsheets:
http://developer.force.com/cheatsheets 102013
Standard Classes and Methods (Subset)
System
abor t J ob asser t asser t Equal s
asser t Not Equal s cur r ent PageRef er ence cur r ent Ti meMi l l i s
debug i sRunni ngTest now
pr ocess r eset Passwor d r unAs schedul e
schedul eBat ch set Passwor d submi t t oday
Math
abs acos asi n at an at an2 cbr t cei l
cos cosh exp f l oor l og l og10 max
mi n mod pow r andom r i nt r ound r oundToLong
si gnum si n si nh sqr t t an t anh
Describe
f i el ds f i el dSet s get Chi l dRel at i onshi ps
get KeyPr ef i x get Label get Label Pl ur al
get Local Name get Name get Recor dTypeI nf os
get Recor dTypeI nf osByI D get Sobj ect Type
i sAccessi bl e get Recor dTypeI nf osByName
i sCr eat eabl e i sCust om i sCust omSet t i ng
i sDel et abl e i sDepr ecat edAndHi dden i sFeedEnabl ed
i sMer geabl e i sQuer yabl e i sSear chabl e
i sUndel et abl e i sUpdat eabl e
Schema. Recor dTypeI nf o r t ByName = r t MapByName. get ( r t . name) ;
Schema. Descr i beSObj ect Resul t d = Schema. SObj ect Type. Account ;
DescribeFieldResult
get Byt eLengt h get Cal cul at edFor mul a get Cont r ol l er
get Def aul t Val ue get Def aul t Val ueFor mul a get Di gi t s
get I nl i neHel pText get Label get Lengt h
get Local Name get Name get Pi ckl i st Val ues
get Pr eci si on get Ref er enceTo get Rel at i onshi pName
get Rel at i onshi pOr der get Scal e get SOAPType
get SObj ect Fi el d get Type i sAccessi bl e
i sAut oNumber i sCal cul at ed i sCaseSensi t i ve
i sCr eat eabl e i sCust om i sDef aul t edOnCr eat e
i sDependant Pi ckl i st i sDepr ecat edAndHi dden i sExt er nal I D
i sFi l t er abl e i sGr oupabl e i sHt ml For mat t ed
i sI dLookup i sNameFi el d i sNamePoi nt i ng
i sNi l l abl e i sPer mi ssi onabl e i sRest r i ct edDel et e
i sRest r i ct edPi ckl i st i sSor t abl e i sUni que
i sUpdat eabl e i sWr i t eRequi r esMast er Read
Schema. Descr i beFi el dResul t f = Schema. SObj ect Type. Account . f i el ds. Name;
LoggingLevel
ERROR WARN I NFO DEBUG FI NE FI NER FI NEST
get Aggr egat eQuer i es get Li mi t Aggr egat eQuer i es
get Cal l out s get Li mi t Cal l out s
get Chi l dRel at i onshi psDescr i bes get DMLRows
get Li mi t Chi l dRel at i onshi psDescr i bes get Li mi t DMLRows
get CPUTi me get Li mi t CPUTi me
get DMLRows get Li mi t DMLRows
get DMLSt at ement s get Li mi t DMLSt at ement s
get Emai l I nvocat i ons get Li mi t Emai l I nvocat i ons
get Fi el dsDescr i bes get Li mi t Fi el dsDescr i bes
get Fi ndSi mi l ar Cal l s get Li mi t Fi ndSi mi l ar Cal l s
get Fut ur eCal l s get Li mi t Fut ur eCal l s
get HeapSi ze get Li mi t HeapSi ze
get Pi ckl i st Descr i bes get Li mi t Pi ckl i st Descr i bes
get Quer i es get Li mi t Quer i es
get Quer yLocat or Rows get Li mi t Quer yLocat or Rows
get Quer yRows get Li mi t Quer yRows
get Recor dTypesDescr i bes get Li mi t Recor dTypesDescr i bes
get RunAs get Li mi t RunAs
get Savepoi nt Rol l backs get Li mi t Savepoi nt Rol l backs
get Savepoi nt s get Li mi t Savepoi nt s
get Sosl Quer i es get Li mi t Sosl Quer i es
UserInfo
get Def aul t Cur r ency get Fi r st Name get Language
get Last Name get Local e get Name
get Or gani zat i onI d get Or gani zat i onName get Pr of i l eI d
get Sessi onI d get UI Theme get UI ThemeDi spl ayed
I sMul t i Cur r encyOr gani zat i on
St r i ng r esul t = User I nf o. get Local e( ) ;
Syst em. asser t Equal s( ' en_US' , r esul t ) ;

S-ar putea să vă placă și