Salesforce Apex Language Reference
Salesforce Apex Language Reference
0: Summer 14
names and marks. Other marks appearing herein may be trademarks of their respective owners.
Table of Contents
Table of Contents
Getting Started....................................................................................................................................1
Chapter 1: Introduction..............................................................................................................1
Introducing Apex..........................................................................................................................................................2
What is Apex?...............................................................................................................................................................2
When Should I Use Apex?............................................................................................................................................4
How Does Apex Work?................................................................................................................................................5
Developing Code in the Cloud.....................................................................................................................................6
What's New?.................................................................................................................................................................6
Understanding Apex Core Concepts.............................................................................................................................7
Writing Apex.....................................................................................................................................25
Chapter 4: Data Types and Variables..........................................................................................25
Data Types..................................................................................................................................................................26
Primitive Data Types...................................................................................................................................................26
Collections...................................................................................................................................................................29
Lists.................................................................................................................................................................29
Sets..................................................................................................................................................................32
Maps................................................................................................................................................................32
Parameterized Typing......................................................................................................................................33
Enums.........................................................................................................................................................................34
Variables......................................................................................................................................................................36
Constants.....................................................................................................................................................................37
Expressions and Operators..........................................................................................................................................38
Understanding Expressions.............................................................................................................................38
Table of Contents
ii
Table of Contents
Table of Contents
iv
Table of Contents
Table of Contents
Finishing Touches............................................................................................................................354
Chapter 12: Debugging Apex...................................................................................................354
Understanding the Debug Log..................................................................................................................................355
Working with Logs in the Developer Console..............................................................................................359
Debugging Apex API Calls...........................................................................................................................371
Exceptions in Apex....................................................................................................................................................372
Exception Statements....................................................................................................................................373
Exception Handling Example.......................................................................................................................374
Built-In Exceptions and Common Methods.................................................................................................376
Catching Different Exception Types.............................................................................................................380
Creating Custom Exceptions.........................................................................................................................381
vi
Table of Contents
Table of Contents
Action Class..............................................................................................................................................................426
Action Constructors......................................................................................................................................427
Action Methods.............................................................................................................................................428
Component Class......................................................................................................................................................428
Dynamic Component Properties...................................................................................................................428
IdeaStandardController Class...................................................................................................................................430
IdeaStandardController Methods..................................................................................................................431
IdeaStandardSetController Class..............................................................................................................................432
IdeaStandardSetController Methods.............................................................................................................434
KnowledgeArticleVersionStandardController Class.................................................................................................435
KnowledgeArticleVersionStandardController Constructors.........................................................................437
KnowledgeArticleVersionStandardController Methods................................................................................437
Message Class............................................................................................................................................................438
Message Constructors....................................................................................................................................439
Message Methods..........................................................................................................................................441
StandardController Class..........................................................................................................................................442
StandardController Constructors..................................................................................................................443
StandardController Methods.........................................................................................................................443
StandardSetController Class.....................................................................................................................................447
StandardSetController Constructors.............................................................................................................448
StandardSetController Methods....................................................................................................................449
Approval Namespace.............................................................................................................................................................455
ProcessRequest Class.................................................................................................................................................455
ProcessRequest Methods...............................................................................................................................455
ProcessResult Class...................................................................................................................................................457
ProcessResult Methods..................................................................................................................................457
ProcessSubmitRequest Class.....................................................................................................................................459
ProcessSubmitRequest Methods...................................................................................................................459
ProcessWorkitemRequest Class................................................................................................................................460
ProcessWorkitemRequest Methods..............................................................................................................460
Auth Namespace...................................................................................................................................................................462
AuthToken Class......................................................................................................................................................462
AuthToken Methods.....................................................................................................................................462
RegistrationHandler Interface...................................................................................................................................464
RegistrationHandler Methods.......................................................................................................................464
Storing User Information and Getting Access Tokens..................................................................................466
Auth.RegistrationHandler Example Implementation...................................................................................467
UserData Class..........................................................................................................................................................468
UserData Constructors..................................................................................................................................468
UserData Properties.......................................................................................................................................469
Canvas Namespace................................................................................................................................................................472
ApplicationContext Interface....................................................................................................................................473
ApplicationContext Methods........................................................................................................................473
CanvasLifecycleHandler Interface.............................................................................................................................476
viii
Table of Contents
CanvasLifecycleHandler Methods.................................................................................................................476
ContextTypeEnum Enum.........................................................................................................................................478
EnvironmentContext Interface..................................................................................................................................478
EnvironmentContext Methods.....................................................................................................................479
RenderContext Interface...........................................................................................................................................484
RenderContext Methods...............................................................................................................................484
Test Class..................................................................................................................................................................486
Test Constants...............................................................................................................................................486
Test Methods................................................................................................................................................487
Canvas Exceptions.....................................................................................................................................................489
ChatterAnswers Namespace..................................................................................................................................................490
AccountCreator Interface..........................................................................................................................................490
AccountCreator Methods..............................................................................................................................490
AccountCreator Example Implementation....................................................................................................491
ConnectApi Namespace........................................................................................................................................................492
Announcements Class...............................................................................................................................................493
Announcements Methods.............................................................................................................................494
Chatter Class.............................................................................................................................................................496
Chatter Methods...........................................................................................................................................497
ChatterFavorites Class...............................................................................................................................................500
ChatterFavorites Methods.............................................................................................................................501
ChatterFeeds Class....................................................................................................................................................520
ChatterFeeds Methods..................................................................................................................................520
ChatterGroups Class.................................................................................................................................................724
ChatterGroups Methods...............................................................................................................................724
ChatterMessages Class..............................................................................................................................................756
ChatterMessages Methods............................................................................................................................756
ChatterUsers Class....................................................................................................................................................779
ChatterUsers Methods..................................................................................................................................779
Communities Class...................................................................................................................................................804
Communities Methods..................................................................................................................................804
CommunityModeration Class...................................................................................................................................806
CommunityModeration Methods.................................................................................................................806
Organization Class....................................................................................................................................................817
Organization Methods..................................................................................................................................818
Mentions Class..........................................................................................................................................................818
Mentions Methods........................................................................................................................................818
RecordDetails Class...................................................................................................................................................824
RecordDetails Methods.................................................................................................................................824
Records Class............................................................................................................................................................827
Records Methods...........................................................................................................................................827
Topics Class..............................................................................................................................................................829
Topics Methods.............................................................................................................................................830
UserProfiles Class......................................................................................................................................................857
ix
Table of Contents
UserProfiles Methods....................................................................................................................................857
Zones Class...............................................................................................................................................................857
Zones Methods..............................................................................................................................................858
ConnectApi Input Classes.........................................................................................................................................864
ConnectApi.AnnouncementInput Class.......................................................................................................864
ConnectApi.BinaryInput Class.....................................................................................................................865
ConnectApi.CanvasAttachmentInput Class.................................................................................................865
ConnectApi.ChatterGroupInput Class.........................................................................................................865
ConnectApi.CommentInput Class................................................................................................................866
ConnectApi.ContentAttachmentInput Class................................................................................................866
ConnectApi.FeedElementInput Class...........................................................................................................867
ConnectApi.FeedItemAttachmentInput Class..............................................................................................867
ConnectApi.FeedItemInput Class.................................................................................................................867
ConnectApi.GroupInformationInput Class..................................................................................................868
ConnectApi.HashtagSegmentInput Class.....................................................................................................868
ConnectApi.LinkAttachmentInput Class.....................................................................................................868
ConnectApi.LinkSegmentInput Class..........................................................................................................868
ConnectApi.MentionSegmentInput Class....................................................................................................869
ConnectApi.MessageBodyInput Class..........................................................................................................869
ConnectApi.MessageSegmentInput Class....................................................................................................869
ConnectApi.NewFileAttachmentInput Class...............................................................................................869
ConnectApi.PhotoInput Class......................................................................................................................870
ConnectApi.PollAttachmentInput Class.......................................................................................................870
ConnectApi.TextSegmentInput Class...........................................................................................................870
ConnectApi.TopicInput Class.......................................................................................................................870
ConnectApi.UserInput Class.........................................................................................................................871
ConnectApi Output Classes......................................................................................................................................871
ConnectApi.AbstractBundleCapability Class...............................................................................................871
ConnectApi.AbstractMessageBody Class.....................................................................................................872
ConnectApi.AbstractRecordField Class........................................................................................................872
ConnectApi.AbstractRecordView Class........................................................................................................873
ConnectApi.Actor Class................................................................................................................................873
ConnectApi.ActorWithId Class....................................................................................................................874
ConnectApi.Address Class............................................................................................................................874
ConnectApi.Announcement..........................................................................................................................874
ConnectApi.AnnouncementPage..................................................................................................................875
ConnectApi.ApprovalAttachment Class.......................................................................................................875
ConnectApi.ApprovalPostTemplateField Class............................................................................................876
ConnectApi.BannerCapability Class.............................................................................................................876
ConnectApi.BasicTemplateAttachment Class..............................................................................................876
ConnectApi.BatchResult...............................................................................................................................877
ConnectApi.BlankRecordField Class............................................................................................................879
ConnectApi.BookmarksCapability Class......................................................................................................879
ConnectApi.Bundle Class.............................................................................................................................879
Table of Contents
ConnectApi.CanvasTemplateAttachment Class...........................................................................................880
ConnectApi.CaseComment Class.................................................................................................................880
ConnectApi.ChatterActivity Class................................................................................................................881
ConnectApi.ChatterConversation Class.......................................................................................................881
ConnectApi.ChatterConversationPage Class................................................................................................881
ConnectApi.ChatterConversationSummary Class........................................................................................882
ConnectApi.ChatterGroup Class..................................................................................................................882
ConnectApi.ChatterGroupDetail Class........................................................................................................883
ConnectApi.ChatterGroupPage Class..........................................................................................................884
ConnectApi.ChatterGroupSummary Class...................................................................................................884
ConnectApi.ChatterGroupSummaryPage Class...........................................................................................884
ConnectApi.ChatterLike Class.....................................................................................................................884
ConnectApi.ChatterLikePage Class..............................................................................................................885
ConnectApi.ChatterLikesCapability Class...................................................................................................885
ConnectApi.ChatterMessage Class...............................................................................................................885
ConnectApi.ChatterMessagePage Class.......................................................................................................886
ConnectApi.ClientInfo Class........................................................................................................................886
ConnectApi.Comment Class........................................................................................................................886
ConnectApi.CommentPage Class.................................................................................................................887
ConnectApi.CommentsCapability Class.......................................................................................................888
ConnectApi.Community Class.....................................................................................................................888
ConnectApi.CommunityPage Class..............................................................................................................889
ConnectApi.ComplexSegment Class............................................................................................................889
ConnectApi.CompoundRecordField Class...................................................................................................889
ConnectApi.ContentAttachment Class........................................................................................................889
ConnectApi.CurrencyRecordField Class.......................................................................................................891
ConnectApi.DashboardComponentAttachment Class.................................................................................891
ConnectApi.DateRecordField Class.............................................................................................................891
ConnectApi.EmailAddress Class..................................................................................................................891
ConnectApi.EmailMessage Class..................................................................................................................892
ConnectApi.EntityLinkSegment Class.........................................................................................................892
ConnectApi.Features Class...........................................................................................................................892
ConnectApi.Feed Class.................................................................................................................................894
ConnectApi.FeedBody Class.........................................................................................................................894
ConnectApi.FeedDirectory Class..................................................................................................................894
ConnectApi.FeedDirectoryItem Class..........................................................................................................894
ConnectApi.FeedElement Class...................................................................................................................895
ConnectApi.FeedElementCapabilities Class.................................................................................................897
ConnectApi.FeedElementCapability Class...................................................................................................897
ConnectApi.FeedElementPage Class............................................................................................................898
ConnectApi.FeedFavorite Class....................................................................................................................899
ConnectApi.FeedFavorites Class...................................................................................................................899
ConnectApi.FeedItem Class.........................................................................................................................899
ConnectApi.FeedItemAttachment Class......................................................................................................903
xi
Table of Contents
ConnectApi.FeedItemPage Class..................................................................................................................903
ConnectApi.FeedItemTopicPage Class........................................................................................................904
ConnectApi.FeedModifiedInfo Class...........................................................................................................904
ConnectApi.FeedPoll Class...........................................................................................................................904
ConnectApi.FeedPollChoice Class...............................................................................................................905
ConnectApi.FieldChangeSegment Class......................................................................................................905
ConnectApi.FieldChangeNameSegment Class.............................................................................................905
ConnectApi.FieldChangeValueSegment Class.............................................................................................905
ConnectApi.File Class...................................................................................................................................905
ConnectApi.FileSummary Class...................................................................................................................907
ConnectApi.FollowerPage Class...................................................................................................................908
ConnectApi.FollowingCounts Class.............................................................................................................908
ConnectApi.FollowingPage Class.................................................................................................................908
ConnectApi.GenericBundleCapability Class................................................................................................909
ConnectApi.GlobalInfluence Class...............................................................................................................909
ConnectApi.GroupChatterSettings Class.....................................................................................................909
ConnectApi.GroupInformation Class...........................................................................................................909
ConnectApi.GroupMember Class.................................................................................................................909
ConnectApi.GroupMemberPage Class.........................................................................................................910
ConnectApi.GroupMembershipRequest Class.............................................................................................910
ConnectApi.GroupMembershipRequests Class............................................................................................911
ConnectApi.HashtagSegment Class.............................................................................................................911
ConnectApi.Icon Class..................................................................................................................................912
ConnectApi.LabeledRecordField Class.........................................................................................................912
ConnectApi.LinkAttachment Class..............................................................................................................912
ConnectApi.LinkSegment Class...................................................................................................................913
ConnectApi.MentionCompletion Class........................................................................................................913
ConnectApi.MentionCompletionPage Class................................................................................................913
ConnectApi.MentionSegment Class.............................................................................................................914
ConnectApi.MentionValidation Class..........................................................................................................914
ConnectApi.MentionValidations Class.........................................................................................................915
ConnectApi.MessageBody Class...................................................................................................................915
ConnectApi.MessageSegment Class.............................................................................................................915
ConnectApi.ModerationCapability Class.....................................................................................................916
ConnectApi.ModerationFlags Class.............................................................................................................916
ConnectApi.MoreChangesSegment Class....................................................................................................917
ConnectApi.Motif Class...............................................................................................................................917
ConnectApi.OrganizationSettings Class.......................................................................................................918
ConnectApi.PercentRecordField Class.........................................................................................................918
ConnectApi.PhoneNumber Class.................................................................................................................918
ConnectApi.Photo Class...............................................................................................................................919
ConnectApi.PicklistRecordField Class.........................................................................................................919
ConnectApi.PollCapability Class..................................................................................................................919
ConnectApi.QuestionAndAnswersCapability...............................................................................................920
xii
Table of Contents
ConnectApi.RecordField Class.....................................................................................................................920
ConnectApi.RecordSnapshotAttachment Class............................................................................................920
ConnectApi.RecordSummary Class..............................................................................................................920
ConnectApi.RecordSummaryList Class........................................................................................................920
ConnectApi.RecordView Class.....................................................................................................................920
ConnectApi.RecordViewSection Class.........................................................................................................921
ConnectApi.Reference Class.........................................................................................................................921
ConnectApi.ReferenceRecordField Class.....................................................................................................921
ConnectApi.ReferenceWithDateRecordField Class.....................................................................................922
ConnectApi.ResourceLinkSegment Class.....................................................................................................922
ConnectApi.Subscription Class.....................................................................................................................922
ConnectApi.TextSegment Class...................................................................................................................922
ConnectApi.TimeZone Class........................................................................................................................922
ConnectApi.Topic Class...............................................................................................................................923
ConnectApi.TopicEndorsement Class..........................................................................................................923
ConnectApi.TopicEndorsementCollection Class.........................................................................................923
ConnectApi.TopicPage Class........................................................................................................................924
ConnectApi.TopicsCapability Class..............................................................................................................924
ConnectApi.TopicSuggestion Class..............................................................................................................924
ConnectApi.TopicSuggestionPage Class......................................................................................................924
ConnectApi.TrackedChangeAttachment Class............................................................................................924
ConnectApi.TrackedChangeBundleCapability.............................................................................................924
ConnectApi.TrackedChangeItem Class........................................................................................................925
ConnectApi.UnauthenticatedUser Class.......................................................................................................925
ConnectApi.UnreadConversationCount Class..............................................................................................925
ConnectApi.User Class.................................................................................................................................925
ConnectApi.UserCapabilities Class...............................................................................................................926
ConnectApi.UserChatterSettings Class........................................................................................................927
ConnectApi.UserDetail Class........................................................................................................................927
ConnectApi.UserGroupPage Class...............................................................................................................928
ConnectApi.UserPage Class..........................................................................................................................928
ConnectApi.UserProfile Class.......................................................................................................................929
ConnectApi.UserProfileTab Class................................................................................................................929
ConnectApi.UserSettings Class.....................................................................................................................929
ConnectApi.UserSummary Class..................................................................................................................930
ConnectApi.Zone Class................................................................................................................................930
ConnectApi.ZonePage Class.........................................................................................................................931
ConnectApi.ZoneSearchPage Class..............................................................................................................931
ConnectApi.ZoneSearchResult Class............................................................................................................932
ConnectApi Enums...................................................................................................................................................932
ConnectApi Exceptions............................................................................................................................................940
Database Namespace.............................................................................................................................................................940
Batchable Interface....................................................................................................................................................941
Batchable Methods........................................................................................................................................941
xiii
Table of Contents
BatchableContext Interface.......................................................................................................................................943
BatchableContext Methods...........................................................................................................................943
DeletedRecord Class.................................................................................................................................................944
DeletedRecord Methods................................................................................................................................944
DeleteResult Class.....................................................................................................................................................945
DeleteResult Methods...................................................................................................................................946
DMLOptions Class...................................................................................................................................................947
DmlOptions Properties.................................................................................................................................947
DmlOptions.AssignmentRuleHeader Class..............................................................................................................949
DmlOptions.AssignmentRuleHeader Properties..........................................................................................950
DmlOptions.EmailHeader Class..............................................................................................................................951
DmlOptions.EmailHeader Properties...........................................................................................................951
EmptyRecycleBinResult Class..................................................................................................................................953
EmptyRecycleBinResult Methods.................................................................................................................953
Error Class.................................................................................................................................................................954
Error Methods...............................................................................................................................................954
GetDeletedResult Class............................................................................................................................................955
GetDeletedResult Methods...........................................................................................................................955
GetUpdatedResult Class...........................................................................................................................................956
GetUpdatedResult Methods..........................................................................................................................956
LeadConvert Class....................................................................................................................................................957
LeadConvert Constructors............................................................................................................................958
LeadConvert Methods...................................................................................................................................958
LeadConvertResult Class..........................................................................................................................................964
LeadConvertResult Methods........................................................................................................................965
MergeResult Class.....................................................................................................................................................966
MergeResult Methods...................................................................................................................................967
QueryLocator Class...................................................................................................................................................968
QueryLocator Methods.................................................................................................................................968
QueryLocatorIterator Class.......................................................................................................................................969
QueryLocatorIterator Methods.....................................................................................................................970
SaveResult Class........................................................................................................................................................970
SaveResult Methods......................................................................................................................................971
UndeleteResult Class.................................................................................................................................................972
UndeleteResult Methods...............................................................................................................................972
UpsertResult Class....................................................................................................................................................973
UpsertResult Methods...................................................................................................................................974
Dom Namespace...................................................................................................................................................................975
Document Class........................................................................................................................................................975
Document Constructors................................................................................................................................975
Document Methods.......................................................................................................................................976
XmlNode Class.........................................................................................................................................................977
XmlNode Methods........................................................................................................................................978
Flow Namespace...................................................................................................................................................................987
xiv
Table of Contents
Interview Class..........................................................................................................................................................987
Interview Methods.........................................................................................................................................988
KbManagement Namespace.................................................................................................................................................989
PublishingService Class.............................................................................................................................................989
PublishingService Methods...........................................................................................................................990
Messaging Namespace........................................................................................................................................................1000
Email Class (Base Email Methods).........................................................................................................................1001
Email Methods............................................................................................................................................1001
EmailFileAttachment Class....................................................................................................................................1004
EmailFileAttachment Constructors.............................................................................................................1004
EmailFileAttachment Methods...................................................................................................................1004
InboundEmail Class................................................................................................................................................1006
InboundEmail Constructors........................................................................................................................1006
InboundEmail Properties............................................................................................................................1006
InboundEmail.BinaryAttachment Class.................................................................................................................1011
InboundEmail.BinaryAttachment Constructors.........................................................................................1011
InboundEmail.BinaryAttachment Properties..............................................................................................1012
InboundEmail.TextAttachment Class....................................................................................................................1012
InboundEmail.TextAttachment Constructors.............................................................................................1013
InboundEmail.TextAttachment Properties.................................................................................................1013
InboundEmailResult Class......................................................................................................................................1015
InboundEmailResult Properties..................................................................................................................1015
InboundEnvelope Class...........................................................................................................................................1015
InboundEnvelope Properties.......................................................................................................................1016
MassEmailMessage Class........................................................................................................................................1016
MassEmailMessage Constructors................................................................................................................1017
MassEmailMessage Methods......................................................................................................................1017
InboundEmail.Header Class...................................................................................................................................1019
InboundEmail.Header Properties................................................................................................................1019
PushNotification Class............................................................................................................................................1020
PushNotification Constructors....................................................................................................................1020
PushNotification Methods..........................................................................................................................1021
PushNotificationPayload Class................................................................................................................................1022
PushNotificationPayload Methods..............................................................................................................1023
SendEmailError Class.............................................................................................................................................1025
SendEmailError Methods...........................................................................................................................1025
SendEmailResult Class............................................................................................................................................1026
SendEmailResult Methods..........................................................................................................................1027
SingleEmailMessage Methods................................................................................................................................1027
SingleEmailMessage Constructors..............................................................................................................1028
SingleEmailMessage Methods....................................................................................................................1028
Process Namespace..............................................................................................................................................................1035
Plugin Interface.......................................................................................................................................................1035
Plugin Methods...........................................................................................................................................1035
xv
Table of Contents
xvi
Table of Contents
FilterOperator Class................................................................................................................................................1071
FilterOperator Methods..............................................................................................................................1071
FilterValue Class.....................................................................................................................................................1072
FilterValue Methods....................................................................................................................................1072
GroupingColumn Class..........................................................................................................................................1072
GroupingColumn Methods.........................................................................................................................1073
GroupingInfo Class.................................................................................................................................................1074
GroupingInfo Methods...............................................................................................................................1074
GroupingValue Class...............................................................................................................................................1075
GroupingValue Methods.............................................................................................................................1075
ReportCurrency Class..............................................................................................................................................1077
ReportCurrency Methods............................................................................................................................1077
ReportDataCell Class..............................................................................................................................................1078
ReportDataCell Methods............................................................................................................................1078
ReportDescribeResult Class....................................................................................................................................1079
ReportDescribeResult Methods..................................................................................................................1079
ReportDetailRow Class...........................................................................................................................................1080
ReportDetailRow Methods.........................................................................................................................1080
ReportExtendedMetadata Class..............................................................................................................................1080
ReportExtendedMetadata Methods............................................................................................................1080
ReportFact Class.....................................................................................................................................................1081
ReportFact Methods....................................................................................................................................1082
ReportFactWithDetails Class..................................................................................................................................1082
ReportFactWithDetails Methods................................................................................................................1082
ReportFilter Class....................................................................................................................................................1083
ReportFilter Constructors............................................................................................................................1084
ReportFilter Methods..................................................................................................................................1084
ReportFormat Enum...............................................................................................................................................1086
ReportInstance Class...............................................................................................................................................1087
ReportInstance Methods.............................................................................................................................1087
ReportManager Class..............................................................................................................................................1089
ReportManager Methods............................................................................................................................1089
ReportMetadata Class.............................................................................................................................................1094
ReportMetadata Methods...........................................................................................................................1094
ReportResults Class.................................................................................................................................................1100
ReportResults Methods...............................................................................................................................1100
ReportType Class....................................................................................................................................................1102
ReportType Methods..................................................................................................................................1102
ReportTypeColumn Class.......................................................................................................................................1103
ReportTypeColumn Methods.....................................................................................................................1103
ReportTypeColumnCategory Class........................................................................................................................1104
ReportTypeColumnCategory Methods.......................................................................................................1105
ReportTypeMetadata Class.....................................................................................................................................1105
ReportTypeMetadata Methods...................................................................................................................1105
xvii
Table of Contents
SummaryValue Class...............................................................................................................................................1106
SummaryValue Methods.............................................................................................................................1106
Reports Exceptions..................................................................................................................................................1107
Schema Namespace.............................................................................................................................................................1107
ChildRelationship Class..........................................................................................................................................1108
ChildRelationship Methods........................................................................................................................1109
DataCategory Class.................................................................................................................................................1110
DataCategory Methods...............................................................................................................................1111
DataCategoryGroupSobjectTypePair Class............................................................................................................1111
DataCategoryGroupSobjectTypePair Constructors....................................................................................1112
DataCategoryGroupSobjectTypePair Methods..........................................................................................1112
DescribeColorResult Class......................................................................................................................................1113
DescribeColorResult Methods....................................................................................................................1114
DescribeDataCategoryGroupResult Class..............................................................................................................1115
DescribeDataCategoryGroupResult Methods.............................................................................................1116
DescribeDataCategoryGroupStructureResult Class................................................................................................1117
DescribeDataCategoryGroupStructureResult Methods..............................................................................1118
DescribeFieldResult Class.......................................................................................................................................1119
DescribeFieldResult Methods.....................................................................................................................1119
DescribeIconResult Class........................................................................................................................................1133
DescribeIconResult Methods......................................................................................................................1133
DescribeSObjectResult Class..................................................................................................................................1135
DescribeSObjectResult Methods.................................................................................................................1135
DescribeTabResult Class.........................................................................................................................................1143
DescribeTabResult Methods.......................................................................................................................1143
DescribeTabSetResult Class....................................................................................................................................1145
DescribeTabSetResult Methods..................................................................................................................1146
DisplayType Enum.................................................................................................................................................1148
FieldSet Class..........................................................................................................................................................1149
FieldSet Methods........................................................................................................................................1150
FieldSetMember Class............................................................................................................................................1152
FieldSetMember Methods...........................................................................................................................1153
PicklistEntry Class..................................................................................................................................................1154
PicklistEntry Methods.................................................................................................................................1155
RecordTypeInfo Class.............................................................................................................................................1156
RecordTypeInfo Methods...........................................................................................................................1156
SOAPType Enum...................................................................................................................................................1158
SObjectField Class..................................................................................................................................................1158
sObjectField Methods.................................................................................................................................1158
SObjectType Class..................................................................................................................................................1159
SObjectType Methods................................................................................................................................1159
Site Namespace...................................................................................................................................................................1161
UrlRewriter Interface...............................................................................................................................................1162
UrlRewriter Methods..................................................................................................................................1162
xviii
Table of Contents
Support Namespace.............................................................................................................................................................1163
EmailTemplateSelector Interface............................................................................................................................1163
EmailTemplateSelector Methods................................................................................................................1164
EmailTemplateSelector Example Implementation......................................................................................1164
MilestoneTriggerTimeCalculator Interface.............................................................................................................1165
MilestoneTriggerTimeCalculator Methods................................................................................................1166
MilestoneTriggerTimeCalculator Example Implementation......................................................................1166
System Namespace..............................................................................................................................................................1167
Answers Class..........................................................................................................................................................1171
Answers Methods........................................................................................................................................1172
ApexPages Class......................................................................................................................................................1173
ApexPages Methods....................................................................................................................................1173
Approval Class.........................................................................................................................................................1176
Approval Methods.......................................................................................................................................1176
Blob Class................................................................................................................................................................1178
Blob Methods..............................................................................................................................................1178
Boolean Class..........................................................................................................................................................1180
Boolean Methods.........................................................................................................................................1180
BusinessHours Class................................................................................................................................................1181
BusinessHours Methods..............................................................................................................................1181
Cases Class..............................................................................................................................................................1184
Cases Methods............................................................................................................................................1184
Comparable Interface..............................................................................................................................................1185
Comparable Methods..................................................................................................................................1186
Comparable Example Implementation........................................................................................................1186
Cookie Class............................................................................................................................................................1187
Cookie Constructors....................................................................................................................................1189
Cookie Methods..........................................................................................................................................1189
Crypto Class............................................................................................................................................................1191
Crypto Methods..........................................................................................................................................1192
Custom Settings Methods.......................................................................................................................................1200
List Custom Setting Methods.....................................................................................................................1205
Hierarchy Custom Setting Methods...........................................................................................................1207
Database Class.........................................................................................................................................................1210
Database Methods.......................................................................................................................................1211
Date Class...............................................................................................................................................................1237
Date Methods..............................................................................................................................................1237
Datetime Methods..................................................................................................................................................1246
Datetime Methods.......................................................................................................................................1246
Decimal Class..........................................................................................................................................................1264
Rounding Mode..........................................................................................................................................1265
Decimal Methods........................................................................................................................................1266
Double Class...........................................................................................................................................................1274
Double Methods..........................................................................................................................................1275
xix
Table of Contents
EncodingUtil Class.................................................................................................................................................1277
EncodingUtil Methods................................................................................................................................1278
Enum Methods.......................................................................................................................................................1281
Exception Class and Built-In Exceptions................................................................................................................1281
Http Class...............................................................................................................................................................1284
Http Methods..............................................................................................................................................1284
HttpCalloutMock Interface.....................................................................................................................................1285
HttpCalloutMock Methods........................................................................................................................1285
HttpRequest Class...................................................................................................................................................1286
HttpRequest Constructors...........................................................................................................................1287
HttpRequest Methods.................................................................................................................................1287
HttpResponse Class................................................................................................................................................1294
HttpResponse Methods...............................................................................................................................1295
Id Class....................................................................................................................................................................1300
Id Methods..................................................................................................................................................1301
Ideas Class...............................................................................................................................................................1304
Ideas Methods.............................................................................................................................................1307
InstallHandler Interface...........................................................................................................................................1309
InstallHandler Methods..............................................................................................................................1310
InstallHandler Example Implementation....................................................................................................1310
Integer Class............................................................................................................................................................1312
Integer Methods..........................................................................................................................................1312
JSON Class.............................................................................................................................................................1313
JSON Methods............................................................................................................................................1314
JSONGenerator Class.............................................................................................................................................1318
JSONGenerator Methods...........................................................................................................................1319
JSONParser Class....................................................................................................................................................1331
JSONParser Methods..................................................................................................................................1331
JSONToken Enum.................................................................................................................................................1342
Limits Class.............................................................................................................................................................1342
Limits Methods...........................................................................................................................................1343
List Class.................................................................................................................................................................1357
List Constructors.........................................................................................................................................1357
List Methods...............................................................................................................................................1359
Long Class...............................................................................................................................................................1369
Long Methods.............................................................................................................................................1370
Map Class................................................................................................................................................................1371
Map Constructors........................................................................................................................................1371
Map Methods..............................................................................................................................................1373
Matcher Class..........................................................................................................................................................1381
Matcher Methods........................................................................................................................................1382
Math Class..............................................................................................................................................................1393
Math Methods.............................................................................................................................................1393
Messaging Class......................................................................................................................................................1416
xx
Table of Contents
Messaging Methods.....................................................................................................................................1416
MultiStaticResourceCalloutMock Class.................................................................................................................1419
MultiStaticResourceCalloutMock Constructors.........................................................................................1419
MultiStaticResourceCalloutMock Methods................................................................................................1419
Network Class.........................................................................................................................................................1421
Network Constructors.................................................................................................................................1421
Network Methods........................................................................................................................................1422
PageReference Class................................................................................................................................................1423
PageReference Constructors........................................................................................................................1426
PageReference Methods..............................................................................................................................1427
Pattern Class............................................................................................................................................................1432
Pattern Methods..........................................................................................................................................1432
QuickAction Class...................................................................................................................................................1435
QuickAction Methods.................................................................................................................................1436
ResetPasswordResult Class.....................................................................................................................................1439
ResetPasswordResult Methods....................................................................................................................1439
RestContext Class...................................................................................................................................................1440
RestContext Properties................................................................................................................................1440
RestRequest Class...................................................................................................................................................1441
RestRequest Constructors...........................................................................................................................1442
RestRequest Properties................................................................................................................................1442
RestRequest Methods..................................................................................................................................1445
RestResponse Class.................................................................................................................................................1446
RestResponse Constructors.........................................................................................................................1446
RestResponse Properties..............................................................................................................................1447
RestResponse Methods...............................................................................................................................1448
Schedulable Interface...............................................................................................................................................1449
Schedulable Methods...................................................................................................................................1450
SchedulableContext Interface..................................................................................................................................1450
SchedulableContext Methods......................................................................................................................1450
Schema Class...........................................................................................................................................................1451
Schema Methods.........................................................................................................................................1451
Search Class.............................................................................................................................................................1455
Search Methods...........................................................................................................................................1455
SelectOption Class..................................................................................................................................................1455
SelectOption Constructors..........................................................................................................................1457
SelectOption Methods.................................................................................................................................1458
Set Class..................................................................................................................................................................1461
Set Constructors..........................................................................................................................................1461
Set Methods................................................................................................................................................1463
Site Class.................................................................................................................................................................1471
Site Methods...............................................................................................................................................1473
sObject Class...........................................................................................................................................................1486
SObject Methods.........................................................................................................................................1486
xxi
Table of Contents
StaticResourceCalloutMock Class...........................................................................................................................1497
StaticResourceCalloutMock Constructors...................................................................................................1497
StaticResourceCalloutMock Methods.........................................................................................................1498
String Class.............................................................................................................................................................1499
String Methods............................................................................................................................................1499
System Class............................................................................................................................................................1561
System Methods..........................................................................................................................................1561
Test Class................................................................................................................................................................1579
Test Methods..............................................................................................................................................1579
Time Class...............................................................................................................................................................1587
Time Methods.............................................................................................................................................1587
TimeZone Class......................................................................................................................................................1590
TimeZone Methods....................................................................................................................................1591
Type Class...............................................................................................................................................................1593
Type Methods.............................................................................................................................................1594
UninstallHandler Interface......................................................................................................................................1598
UninstallHandler Methods..........................................................................................................................1599
UninstallHandler Example Implementation................................................................................................1600
URL Class...............................................................................................................................................................1601
URL Constructors.......................................................................................................................................1602
URL Methods.............................................................................................................................................1604
UserInfo Class.........................................................................................................................................................1609
UserInfo Methods.......................................................................................................................................1609
Version Class...........................................................................................................................................................1616
Version Constructors...................................................................................................................................1616
Version Methods.........................................................................................................................................1617
WebServiceMock Interface.....................................................................................................................................1619
WebServiceMock Methods.........................................................................................................................1619
XmlStreamReader Class..........................................................................................................................................1620
XmlStreamReader Constructors..................................................................................................................1621
XmlStreamReader Methods........................................................................................................................1621
XmlStreamWriter Class..........................................................................................................................................1633
XmlStreamWriter Constructors..................................................................................................................1633
XmlStreamWriter Methods.........................................................................................................................1633
Appendices.....................................................................................................................................1640
Appendix A: SOAP API and SOAP Headers for Apex.............................................................1640
ApexTestQueueItem...............................................................................................................................................1641
ApexTestResult.......................................................................................................................................................1642
compileAndTest()...................................................................................................................................................1645
CompileAndTestRequest............................................................................................................................1646
CompileAndTestResult...............................................................................................................................1647
compileClasses()......................................................................................................................................................1649
compileTriggers()....................................................................................................................................................1650
xxii
Table of Contents
executeanonymous()................................................................................................................................................1650
ExecuteAnonymousResult...........................................................................................................................1651
runTests()................................................................................................................................................................1651
RunTestsRequest.........................................................................................................................................1653
RunTestsResult...........................................................................................................................................1653
DebuggingHeader...................................................................................................................................................1656
PackageVersionHeader............................................................................................................................................1657
xxiii
GETTING STARTED
Chapter 1
Introduction
In this chapter ...
Introducing Apex
What is Apex?
When Should I Use Apex?
How Does Apex Work?
Developing Code in the Cloud
What's New?
Understanding Apex Core Concepts
In this chapter, youll learn about the Apex programming language, how it
works, and when to use it.
Introduction
Introducing Apex
Introducing Apex
Salesforce.com has changed the way organizations do business by moving enterprise applications that were traditionally
client-server-based into an on-demand, multitenant Web environment, the Force.com platform. This environment allows
organizations to run and customize applications, such as Salesforce Automation and Service & Support, and build new custom
applications based on particular business needs.
While many customization options are available through the Salesforce user interface, such as the ability to define new fields,
objects, workflow, and approval processes, developers can also use the SOAP API to issue data manipulation commands such
as delete(), update() or upsert(), from client-side programs.
These client-side programs, typically written in Java, JavaScript, .NET, or other programming languages grant organizations
more flexibility in their customizations. However, because the controlling logic for these client-side programs is not located
on Force.com platform servers, they are restricted by:
The performance costs of making multiple round-trips to the salesforce.com site to accomplish common business transactions
The cost and complexity of hosting server code, such as Java or .NET, in a secure and robust environment
To address these issues, and to revolutionize the way that developers create on-demand applications, salesforce.com introduces
Force.com Apex code, the first multitenant, on-demand programming language for developers interested in building the next
generation of business applications.
What is Apex?more about when to use Apex, the development process, and some limitations
What's new in this Apex release?
Apex Quick Startdelve straight into the code and write your first Apex class and trigger
What is Apex?
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java
and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button
clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on
objects.
Introduction
What is Apex?
Introduction
Data focused
Apex is designed to thread together multiple query and DML statements into a single unit of work on the Force.com
platform server, much as developers use database stored procedures to thread together multiple transaction statements
on a database server. Note that like other database stored procedures, Apex does not attempt to provide general support
for rendering elements in the user interface.
Rigorous
Apex is a strongly-typed language that uses direct references to schema objects such as object and field names. It fails
quickly at compile time if any references are invalid, and stores all custom field, object, and class dependencies in metadata
to ensure they are not deleted while required by active Apex code.
Hosted
Apex is interpreted, executed, and controlled entirely by the Force.com platform.
Multitenant aware
Like the rest of the Force.com platform, Apex runs in a multitenant environment. Consequently, the Apex runtime
engine is designed to guard closely against runaway code, preventing them from monopolizing shared resources. Any
code that violate these limits fail with easy-to-understand error messages.
Automatically upgradeable
Apex never needs to be rewritten when other parts of the Force.com platform are upgraded. Because the compiled code
is stored as metadata in the platform, it always gets automatically upgraded with the rest of the system.
Easy to test
Apex provides built-in support for unit test creation and execution, including test results that indicate how much code
is covered, and which parts of your code could be more efficient. Salesforce.com ensures that Apex code always work as
expected by executing all unit tests stored in metadata prior to any platform upgrades.
Versioned
You can save your Apex code against different versions of the Force.com API. This enables you to maintain behavior.
Apex is included in Performance Edition, Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com.
Apex
Use Apex if you want to:
Introduction
Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed,
regardless of whether it originates in the user interface, a Visualforce page, or from SOAP API.
Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and
customizing the Salesforce user interface. With Visualforce you can:
SOAP API
Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of
record at a time and does not require any transactional control (such as setting a Savepoint or rolling back changes).
For more information, see the SOAP API Developer's Guide.
Figure 2: Apex is compiled, stored, and run entirely on the Force.com platform.
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an
abstract set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as
metadata.
When an end-user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform
application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before
returning the result. The end-user observes no differences in execution time from standard platform requests.
Introduction
See Also:
Trigger and Bulk Request Best Practices
What's New?
Review the Summer 14 Release Notes to learn about new and changed Apex features in Summer 14.
Past Releases
For information about new features introduced in previous releases, see:
Introduction
Introduction
For more information about using version settings with managed packages, see About Package Versions in the Salesforce
online help.
Tip: Note that the semi-colon at the end of the above is not optional. You must end all statements with a semi-colon.
In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any
changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments
are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method
returns, the passed-in argument still references the same object as before the method call and can't be changed to point to
another object. However, the values of the object's fields can be changed in the method.
Using Statements
A statement is any coded instruction that performs an action.
In Apex, statements must end with a semicolon and can be one of the following types:
Introduction
Conditional (if-else)
Loops:
Do-while
While
For
Locking
Data Manipulation Language (DML)
Transaction Control
Method Invoking
Exception Handling
A block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement
would be allowed. For example:
if (true) {
System.debug(1);
System.debug(2);
} else {
System.debug(3);
System.debug(4);
}
In cases where a block consists of only one statement, the curly braces can be left off. For example:
if (true)
System.debug(1);
else
System.debug(2);
Using Collections
Apex has the following types of collections:
Lists (arrays)
Maps
Sets
A list is a collection of elements, such as Integers, Strings, objects, or other collections. Use a list when the sequence of elements
is important. You can have duplicate elements in a list.
The first index position in a list is always 0.
To create a list:
Introduction
The following example creates a list of Integer, and assigns it to the variable My_List. Remember, because Apex is strongly
typed, you must declare the data type of My_List as a list of Integer.
List<Integer> My_List = new List<Integer>();
The following example creates a set of String. The values for the set are passed in using the curly braces {}.
Set<String> My_String = new Set<String>{'a', 'b', 'c'};
The following example creates a map that has a data type of Integer for the key and String for the value. In this example, the
values for the map are being passed in between the curly braces {} as the map is being created.
Map<Integer, String> My_Map = new Map<Integer, String>{1 => 'a', 2 => 'b', 3 => 'c'};
10
Introduction
Using Branching
An if statement is a true-false test that enables your application to do different things based on a condition. The basic syntax
is as follows:
if (Condition){
// Do this if the condition is true
} else {
// Do this if the condition is not true
}
Using Loops
While the if statement enables your application to do things based on a condition, loops tell your application to do the same
thing again and again based on a condition. Apex supports the following types of loops:
Do-while
While
For
A Do-while loop checks the condition after the code has executed.
A While loop checks the condition at the start, before the code executes.
A For loop enables you to more finely control the condition used with the loop. In addition, Apex supports traditional For
loops where you set the conditions, as well as For loops that use lists and SOQL queries as part of the condition.
For more information, see Loops on page 49.
11
Chapter 2
Apex Development Process
In this chapter ...
In this chapter, youll learn about the Apex development lifecycle, and which
organization and tools to use to develop Apex. Youll also learn about testing
and deploying Apex code.
12
In addition to deploying your Apex, once it is written and tested, you can also add your classes and triggers to a Force.com
AppExchange App package.
You can't develop Apex in your Salesforce production organization. Live users accessing the system while you're developing
can destabilize your data or corrupt your application. Instead, you must do all your development work in either a sandbox or
a Developer Edition organization.
If you aren't already a member of the developer community, go to http://developer.salesforce.com/signup and
follow the instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free
Developer Edition organization. Even if you already have an Enterprise, Unlimited, or Performance Edition organization and
a sandbox for creating Apex, we strongly recommends that you take advantage of the resources available in the developer
community.
Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.
13
Learning Apex
Has few characters because Salesforce automatically appends the sandbox name to usernames on user records
in the sandbox environment. Names with fewer characters make sandbox logins easier to type.
Learning Apex
After you have your developer account, there are many resources available to you for learning about Apex:
Force.com Workbook: Get Started Building Your First App in the Cloud
Beginning programmers
A set of ten 30-minute tutorials that introduce various Force.com platform features. The Force.com Workbook tutorials
are centered around building a very simple warehouse management system. You'll start developing the application from
the bottom up; that is, you'll first build a database model for keeping track of merchandise. You'll continue by adding
business logic: validation rules to ensure that there is enough stock, workflow to update inventory when something is
sold, approvals to send email notifications for large invoice values, and trigger logic to update the prices in open invoices.
Once the database and business logic are complete, you'll create a user interface to display a product inventory to staff,
a public website to display a product catalog, and then the start of a simple store front. If you'd like to develop offline
and integrate with the app, we've added a final tutorial to use Adobe Flash Builder for Force.com.
Force.com Workbook: HTML | PDF
14
Learning Apex
Apex Workbook
Beginning programmers
The Apex Workbook introduces you to the Apex programming language through a set of tutorials. Youll learn the
fundamentals of Apex and how you can use it on the Force.com platform to add custom business logic through triggers,
unit tests, scheduled Apex, batch Apex, REST Web services, and Visualforce controllers.
Apex Workbook: HTML | PDF
Developer Force Apex Page
Beginning and advanced programmers
The Apex page on Developer Force has links to several resources including articles about the Apex programming language.
These resources provide a quick introduction to Apex and include best practices for Apex development.
Force.com Cookbook
Beginning and advanced programmers
This collaborative site provides many recipes for using the Web services API, developing Apex code, and creating
Visualforce pages. The Force.com Cookbook helps developers become familiar with common Force.com programming
techniques and best practices. You can read and comment on existing recipes, or submit your own recipes, at
http://developer.force.com/cookbook.
Development Life Cycle: Enterprise Development on the Force.com Platform
Architects and advanced programmers
Whether you are an architect, administrator, developer, or manager, the Development Life Cycle Guide prepares you to
undertake the development and release of complex applications on the Force.com platform.
Training Courses
Training classes are also available from salesforce.com Training & Certification. You can find a complete list of courses
at the Training & Certification site.
In This Book (Apex Developer's Guide)
Beginning programmers should look at the following:
Introducing Apex, and in particular:
Documentation Conventions
Core Concepts
Quick Start Tutorial
15
Writing codeYou can add code using the source code editor. Also, you can browse packages in your organization.
Compiling codeWhen you save a trigger or class, the code is automatically compiled. Any compilation errors will be
reported.
DebuggingYou can view debug logs and set checkpoints that aid in debugging.
TestingYou can execute tests of specific test classes or all tests in your organization, and you can view test results. Also,
you can inspect code coverage.
Checking performanceYou can inspect debug logs to locate performance bottlenecks.
SOQL queriesYou can query data in your organization and view the results using the Query Editor.
Color coding and autocompleteThe source code editor uses a color scheme for easier readability of code elements and
provides autocompletion for class and method names.
Force.com IDE
The Force.com IDE is a plug-in for the Eclipse IDE. The Force.com IDE provides a unified interface for building and
deploying Force.com applications. Designed for developers and development teams, the IDE provides tools to accelerate
Force.com application development, including source code editors, test execution tools, wizards and integrated help. This tool
includes basic color-coding, outline view, integrated unit testing, and auto-compilation on save with error message display.
See the website for information about installation and usage.
Note: The Force.com IDE is a free resource provided by salesforce.com to support its users and partners but isn't
considered part of our services for purposes of the salesforce.com Master Subscription Agreement.
Tip: If you want to extend the Eclipse plug-in or develop an Apex IDE of your own, the SOAP API includes methods
for compiling triggers and classes, and executing test methods, while the Metadata API includes methods for deploying
code to production environments. For more information, see Deploying Apex on page 407 and SOAP API and SOAP
Headers for Apex on page 1640.
For a trigger on a standard object, from Setup, click Customize, click the name of the object, and click Triggers. In the
Triggers detail page, click New, and then enter your code in the Body text box.
For a trigger on a custom object, from Setup, click Develop > Objects, and click the name of the object. In the Triggers
related list, click New, and then enter your code in the Body text box.
For a class, from Setup, click Develop > Apex Classes. Click New, and then enter your code in the Body text box.
16
Writing Tests
Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.
Alternatively, you can use any text editor, such as Notepad, to write Apex code. Then either copy and paste the code into your
application, or use one of the API calls to deploy it.
Writing Tests
Testing is the key to successful long-term development and is a critical component of the development process. We strongly
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
development.
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are
class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit
no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the
method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest.
In addition, before you deploy Apex or package it for the Force.com AppExchange, the following must be true.
At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.
When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is
covered. Instead, you should make sure that every use case of your application is covered, including positive and negative
cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.
For more information on writing tests, see Testing Apex on page 384.
17
Note: The Force.com IDE and the Force.com Migration Tool are free resources provided by salesforce.com to
support its users and partners, but aren't considered part of our services for purposes of the salesforce.com Master
Subscription Agreement.
For more information, see Using the Force.com Migration Tool and Deploying Apex.
18
Chapter 3
Apex Quick Start
Once you have a Developer Edition or sandbox organization, you may want to learn some of the core concepts of Apex.
Because Apex is very similar to Java, you may recognize much of the functionality.
After reviewing the basics, you are ready to write your first Apex programa very simple class, trigger, and unit test.
In addition, there is a more complex shipping invoice example that you can also walk through. This example illustrates many
more features of the language.
Note: The Hello World and the shipping invoice samples require custom fields and objects. You can either create
these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com
AppExchange. For more information, see https://developer.salesforce.com/docs.
5. Click Save.
Ta dah! You've now created your first custom object. Now let's create a custom field.
6. In the Custom Fields & Relationships section of the Book detail page, click New.
7. Select Number for the data type and click Next.
8. Enter Price for the field label.
9. Enter 16 in the length text box.
10. Enter 2 in the decimal places text box, and click Next.
11. Click Next to accept the default values for field-level security.
12. Click Save.
Youve just created a custom object called Book, and added a custom field to that custom object. Custom objects already have
some standard fields, like Name and CreatedBy, and allow you to add other fields that are more specific to your implementation.
For this tutorial, the Price field is part of our Book object and it is accessed by the Apex class you will write in the next step.
In this step, you add an Apex class that contains a method for updating the book price. This method is called by the trigger
that you will be adding in the next step.
1. From Setup, click Develop > Apex Classes and click New.
2. In the class editor, enter this class definition:
public class MyHelloWorld {
}
The previous code is the class definition to which you will be adding one method in the next step. Apex code is generally
contained in classes. This class is defined as public, which means the class is available to other Apex classes and triggers.
For more information, see Classes, Objects, and Interfaces on page 53.
3. Add this method definition between the class opening and closing brackets.
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
This method is called applyDiscount, and it is both public and static. Because it is a static method, you don't need to
create an instance of the class to access the methodyou can just use the name of the class followed by a dot (.) and the
name of the method. For more information, see Static and Instance on page 60.
This method takes one parameter, a list of Book records, which is assigned to the variable books. Notice the __c in the
object name Book__c. This indicates that it is a custom object that you created. Standard objects that are provided in the
Salesforce application, such as Account, don't end with this postfix.
20
The next section of code contains the rest of the method definition:
for (Book__c b :books){
b.Price__c *= 0.9;
}
Notice the __c after the field name Price__c. This indicates it is a custom field that you created. Standard fields that are
provided by default in Salesforce are accessed using the same type of dot notation but without the __c, for example, Name
doesn't end with __c in Book__c.Name. The statement b.Price__c *= 0.9; takes the old value of b.Price__c,
multiplies it by 0.9, which means its value will be discounted by 10%, and then stores the new value into the b.Price__c
field. The *= operator is a shortcut. Another way to write this statement is b.Price__c = b.Price__c * 0.9;. See
Understanding Expression Operators on page 39.
4. Click Save to save the new class. You should now have this full class definition.
public class MyHelloWorld {
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
}
You now have a class that contains some code that iterates over a list of books and updates the Price field for each book. This
code is part of the applyDiscount static method called by the trigger that you will create in the next step.
In this step, you create a trigger for the Book__c custom object that calls the applyDiscount method of the MyHelloWorld
class that you created in the previous step.
A trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the
Force.com platform database. Every trigger runs with a set of context variables that provide access to the records that caused
the trigger to fire. All triggers run in bulk; that is, they process several records at once.
1. From Setup, click Create > Objects and click the name of the object you just created, Book.
2. In the triggers section, click New.
3. In the trigger editor, delete the default template code and enter this trigger definition:
trigger HelloWorldTrigger on Book__c (before insert) {
Book__c[] books = Trigger.new;
MyHelloWorld.applyDiscount(books);
}
21
It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example,
this trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into
the database.
The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context
variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and
provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that
are about to be inserted.
Book__c[] books = Trigger.new;
The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new
books.
MyHelloWorld.applyDiscount(books);
You now have all the code that is needed to update the price of all books that get inserted. However, there is still one piece
of the puzzle missing. Unit tests are an important part of writing code and are required. In the next step, you will see why this
is so and you will be able to add a test class.
In this step, you add a test class with one test method. You also run the test and verify code coverage. The test method exercises
and validates the code in the trigger and class. Also, it enables you to reach 100% code coverage for the trigger and class.
Note: Testing is an important part of the development process. Before you can deploy Apex or package it for the
Force.com AppExchange, the following must be true.
At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.
When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code
that is covered. Instead, you should make sure that every use case of your application is covered, including
positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code
being covered by unit tests.
1. From Setup, click Develop > Apex Classes and click New.
2. In the class editor, add this test class definition, and then click Save.
@isTest
private class HelloWorldTestClass {
22
This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage
to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3
MB for all Apex code. You can also add the @isTest annotation to individual methods. For more information, see IsTest
Annotation on page 80 and Understanding Execution Governors and Limits.
The method validateHelloWorld is defined as a testMethod. This means that if any changes are made to the
database, they are automatically rolled back when execution completes and you don't have to delete any test data created
in the test method.
First the test method creates a new book and inserts it into the database temporarily. The System.debug statement writes
the value of the price in the debug log.
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;
Once the book is inserted, the code retrieves the newly inserted book, using the ID that was initially assigned to the book
when it was inserted, and then logs the new price that the trigger modified:
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);
When the MyHelloWorld class runs, it updates the Price__c field and reduces its value by 10%. The following line is
the actual test, verifying that the method applyDiscount actually ran and produced the expected result:
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);
3. Now lets switch to the Developer Console to run this test and view code coverage information. Click Your Name >
Developer Console.
The Developer Console window opens.
4. In the Developer Console, click Test > New Run.
5. To add your test class, click HelloWorldTestClass, and then click >.
6. To run the test, click Run.
The test result displays in the Tests tab. Optionally, you can expand the test class in the Tests tab to view which methods
were run. In this case, the class contains only one test method.
23
7. The Overall Code Coverage pane shows the code coverage of this test class. To view the lines of code in the trigger covered
by this test, which is 100%, double-click the code coverage line for HelloWorldTrigger. Also, because the trigger calls a
method from the MyHelloWorld class, this class has some coverage too (100%). To view the class coverage, double-click
MyHelloWorld.
8. To open the log file, in the Logs tab, double-click the most recent log line in the list of logs. The execution log displays,
including logging information about the trigger event, the call to the applyDiscount class method, and the debug output
of the price before and after the trigger.
By now, you have completed all the steps necessary for writing some Apex code with a test that runs in your development
environment. In the real world, after youve sufficiently tested your code and youre satisfied with it, you want to deploy the
code along with any other prerequisite components to a production organization. The next step will show you how to do this
for the code and custom object youve just created.
In this step, you deploy the Apex code and the custom object you created previously to your production organization using
change sets.
This procedure doesn't apply to Developer organizations since change sets are available only in Performance, Unlimited,
Enterprise, or Database.com Edition organizations. If you have a Developer Edition account, you can use other deployment
methods. For more information, see Deploying Apex.
1.
2.
3.
4.
5.
6.
In this tutorial, you learned how to create a custom object, how to add an Apex trigger, class, and test class. Finally, you also
learned how to test your code, and how to upload the code and the custom object using Change Sets.
24
WRITING APEX
Chapter 4
Data Types and Variables
In this chapter ...
Data Types
Primitive Data Types
Collections
Enums
Variables
Constants
Expressions and Operators
Assignment Statements
Understanding Rules of Conversion
In this chapter youll learn about data types and variables in Apex. Youll also
learn about related language constructsenums, constants, expressions,
operators, and assignment statements.
25
Data Types
Data Types
In Apex, all variables and expressions have a data type that is one of the following:
A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types on page
26)
An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c
(see sObject Types on page 100 in Chapter 4.)
A collection, including:
A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists
on page 29)
A set of primitives (see Sets on page 32)
A map from a primitive to a primitive, sObject, or collection (see Maps on page 32)
A typed list of values, also known as an enum (see Enums on page 34)
Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 53)
Objects created from system supplied Apex classes
Null (for the null constant, which can be assigned to any variable)
Methods can return values of any of the listed types, or return no value and be of type Void.
Type checking is strictly enforced at compile time. For example, the parser generates an error if an object field of type Integer
is assigned a value of type String. However, all compile-time exceptions are returned as specific fault codes, with the line
number and column of the error. For more information, see Debugging Apex on page 354.
Description
Blob
A collection of binary data stored as a single object. You can convert this datatype to String
or from String using the toString and valueOf methods, respectively. Blobs can be accepted
as Web service arguments, stored in a document (the body of a document is a Blob), or sent
as attachments. For more information, see Crypto Class.
Boolean
A value that can only be assigned true, false, or null. For example:
Boolean isWinner = true;
Date
A value that indicates a particular day. Unlike Datetime values, Date values contain no
information about time. Date values must always be created with a system static method.
You cannot manipulate a Date value, such as add days, merely by adding a number to a Date
variable. You must use the Date methods instead.
26
Data Type
Description
Datetime
A value that indicates a particular day and time, such as a timestamp. Datetime values must
always be created with a system static method.
You cannot manipulate a Datetime value, such as add minutes, merely by adding a number
to a Datetime variable. You must use the Datetime methods instead.
Decimal
A number that includes a decimal point. Decimal is an arbitrary precision number. Currency
fields are automatically assigned the type Decimal.
If you do not explicitly set the scale, that is, the number of decimal places, for a Decimal using
the setScale method, the scale is determined by the item from which the Decimal is created.
Double
If the Decimal is created as part of a query, the scale is based on the scale of the field
returned from the query.
If the Decimal is created from a String, the scale is the number of characters after the
decimal point of the String.
If the Decimal is created from a non-decimal number, the scale is determined by converting
the number to a String and then using the number of characters after the decimal point.
A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and
a maximum value of 263-1. For example:
Double d=3.14159;
Note that if you set ID to a 15-character value, Apex automatically converts the value to its
18-character representation. All invalid ID values are rejected with a runtime exception.
Integer
A 32-bit number that does not include a decimal point. Integers have a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647. For example:
Integer i = 1;
Long
A 64-bit number that does not include a decimal point. Longs have a minimum value of -263
and a maximum value of 263-1. Use this datatype when you need a range of values wider than
those provided by Integer. For example:
Long l = 2147483648L;
Object
Any data type that is supported in Apexprimitive data types (such as Integer), user-defined
custom classes, the sObject generic type, or an sObject specific type (such as Account). All
Apex data types inherit from Object.
27
Data Type
Description
You can cast an object that represents a more specific data type to its underlying data type.
For example:
Object obj = 10;
// Cast the object to an integer.
Integer i = (Integer)obj;
System.assertEquals(10, i);
The next example shows how to cast an object to a user-defined typea custom Apex class
named MyApexClass that is predefined in your organization.
Object obj = new MyApexClass();
// Cast the object to the MyApexClass custom type.
MyApexClass mc = (MyApexClass)obj;
// Access a method on the user-defined class.
mc.someClassMethod();
String
String size: Strings have no limit on the number of characters they can include. Instead, the
heap size limit is used to ensure that your Apex programs don't grow too large.
Empty Strings and Trailing Whitespace: sObject String field values follow the same rules
as in the SOAP API: they can never be empty (only null), and they can never include leading
and trailing whitespace. These conventions are necessary for database storage.
Conversely, Strings in Apex can be null or empty, and can include leading and trailing
whitespace (such as might be used to construct a message).
The Solution sObject field SolutionNote operates as a special type of String. If you have
HTML Solutions enabled, any HTML tags used in this field are verified before the object
is created or updated. If invalid HTML is entered, an error is thrown. Any JavaScript used
in this field is removed before the object is created or updated. In the following example,
when the Solution displays on a detail page, the SolutionNote field has H1 HTML formatting
applied to it:
trigger t on Solution (before insert) {
Trigger.new[0].SolutionNote ='<h1>hello</h1>';
}
In the following example, when the Solution displays on a detail page, the SolutionNote field
only contains HelloGoodbye:
trigger t2 on Solution (before insert) {
Trigger.new[0].SolutionNote =
'<javascript>Hello</javascript>Goodbye';
}
For more information, see HTML Solutions Overview in the Salesforce online help.
28
Collections
Data Type
Description
Escape Sequences: All Strings in Apex use the same escape sequences as SOQL strings: \b
(backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote),
\' (single quote), and \\ (backslash).
Comparison Operators: Unlike Java, Apex Strings support use of the comparison operators
==, !=, <, <=, >, and >=. Since Apex uses SOQL comparison semantics, results for Strings
are collated according to the context user's locale, and `are not case sensitive. For more
information, see Operators on page 39.
String Methods: As in Java, Strings can be manipulated with a number of standard methods.
See String Class for information.
Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a
runtime error if you assign a String value that is too long for the field.
Time
A value that indicates a particular time. Time values must always be created with a system
static method. See Time Class.
In addition, two non-standard primitive data types cannot be used as variable or method types, but do appear in system static
methods:
AnyType. The valueOf static method converts an sObject field of type AnyType to a standard primitive. AnyType is
used within the Force.com platform database exclusively for sObject fields in field history tracking tables.
Currency. The Currency.newInstance static method creates a literal of type Currency. This method is for use solely
within SOQL and SOSL WHERE clauses to filter against sObject currency fields. You cannot instantiate Currency in any
other type of Apex.
For more information on the AnyType data type, see Field Types in the Object Reference for Salesforce and Force.com.
Collections
Apex has the following types of collections:
Lists
Maps
Sets
Note: There is no limit on the number of items a collection can hold. However, there is a general limit on heap size.
Lists
A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data typeprimitive
types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table is a visual representation
of a list of Strings:
Index 0
Index 1
Index 2
Index 3
Index 4
Index 5
'Red'
'Orange'
'Yellow'
'Green'
'Blue'
'Purple'
29
Lists
To access elements in a list, use the List methods provided by Apex. For example:
List<Integer> myList = new List<Integer>(); // Define a new list
myList.add(47);
// Adds a second element of value 47 to the end
// of the list
Integer i = myList.get(0);
// Retrieves the element at index 0
myList.set(0, 1);
// Adds the integer 1 to the list at index 0
myList.clear();
// Removes all elements from the list
For more information, including a complete list of all supported methods, see List Class on page 1357.
Using Array Notation for One-Dimensional Lists
When using one-dimensional lists of primitives or objects, you can also use more traditional array notation to declare and
reference list elements. For example, you can declare a one-dimensional list of primitives or objects by following the data type
name with the [] characters:
String[] colors = new List<String>();
To reference an element of a one-dimensional list, you can also follow the name of the list with the element's index position
in square brackets. For example:
colors[0] = 'Green';
Even though the size of the previous String array is defined as one element (the number between the brackets in new
String[1]), lists are elastic and can grow as needed provided that you use the List add method to add new elements. For
example, you can add two or more elements to the colors list. But if youre using square brackets to add an element to a list,
the list behaves like an array and isnt elastic, that is, you wont be allowed to add more elements than the declared array size.
All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example:
Example
Description
Defines an Integer list of size zero with no elements
30
Lists
Example
Description
Defines an Integer list with memory allocated for six Integers
List Sorting
You can sort list elements and the sort order depends on the data type of the elements.
Using the List.sort method, you can sort elements in a list. Sorting is in ascending order for elements of primitive data
types, such as strings. The sort order of other more complex data types is described in the chapters covering those data types.
This example shows how to sort a list of strings and verifies that the colors are in ascending order in the list.
List<String> colors = new List<String>{
'Yellow',
'Red',
'Green'};
colors.sort();
System.assertEquals('Green', colors.get(0));
System.assertEquals('Red', colors.get(1));
System.assertEquals('Yellow', colors.get(2));
For the Visualforce SelectOption control, sorting is in ascending order based on the value and label fields. See this next section
for the sequence of comparison steps used for SelectOption.
Default Sort Order for SelectOption
The List.sort method sorts SelectOption elements in ascending order using the value and label fields, and is based on this
comparison sequence.
1. The value field is used for sorting first.
2. If two value fields have the same value or are both empty, the label field is used.
Note that the disabled field is not used for sorting.
For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.
In this example, a list contains three SelectOption elements. Two elements, United States and Mexico, have the same value
field (A). The List.sort method sorts these two elements based on the label field, and places Mexico before United States,
as shown in the output. The last element in the sorted list is Canada and is sorted on its value field C, which comes after A.
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('A','United States'));
options.add(new SelectOption('C','Canada'));
options.add(new SelectOption('A','Mexico'));
System.debug('Before sorting: ' + options);
options.sort();
System.debug('After sorting: ' + options);
This is the output of the debug statements. It shows the list contents before and after the sort.
DEBUG|Before sorting: (System.SelectOption[value="A", label="United States",
disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"],
System.SelectOption[value="A", label="Mexico", disabled="false"])
DEBUG|After sorting: (System.SelectOption[value="A", label="Mexico", disabled="false"],
System.SelectOption[value="A", label="United States", disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"])
31
Sets
Sets
A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data typeprimitive
types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table represents a set of
strings, that uses city names:
'San Francisco'
'New York'
'Paris'
'Tokyo'
Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers.
A set can contain up to four levels of nested collections inside it, that is, up to five levels overall.
To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
new Set<String>()
To access elements in a set, use the system methods provided by Apex. For example:
Set<Integer> s = new Set<Integer>();
s.add(1);
System.assert(s.contains(1));
s.remove(1);
//
//
//
//
Define
Add an
Assert
Remove
a new set
element to the set
that the set contains an element
the element from the set
For more information, including a complete list of all supported set system methods, see Set Class on page 1461.
Note the following limitations on sets:
Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations
(for example, HashSet or TreeSet). Apex uses a hash structure for all sets.
A set is an unordered collection. Do not rely on the order in which set results are returned. The order of objects returned
by sets may change without warning.
Maps
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data
typeprimitive types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table
represents a map of countries and currencies:
Country (Key)
'United States'
'Japan'
'France'
'England'
'India'
Currency (Value)
'Dollar'
'Yen'
'Euro'
'Pound'
'Rupee'
Map keys and values can contain any collection, and can contain nested collections. For example, you can have a map of
Integers to maps, which, in turn, map Strings to lists. Map keys can contain up to only four levels of nested collections.
32
Parameterized Typing
To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
Map<String, String> country_currencies = new Map<String, String>();
Map<ID, Set<String>> m = new Map<ID, Set<String>>();
You can use the generic or specific sObject data types with maps (youll learn more about maps with sObjects in a later chapter).
You can also create a generic instance of a map.
As with lists, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the
curly braces, specify the key first, then specify the value for that key using =>. For example:
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' =>
'd'.toUpperCase()};
In the first example, the value for the key a is b, and the value for the key c is d.
To access elements in a map, use the Map methods provided by Apex. This example creates a map of integer keys and string
values. It adds two entries, checks for the existence of the first key, retrieves the value for the second entry, and finally gets the
set of all keys.
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry');
// Insert a new key-value pair in the map
m.put(2, 'Second entry');
// Insert a new key-value pair in the map
System.assert(m.containsKey(1)); // Assert that the map contains a key
String value = m.get(2);
// Retrieve a value, given a particular key
System.assertEquals('Second entry', value);
Set<Integer> s = m.keySet();
// Return a set that contains all of the keys in the
map
For more information, including a complete list of all supported Map methods, see Map Class on page 1371.
Map Considerations
Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations
(for example, HashMap or TreeMap). Apex uses a hash structure for all maps.
Do not rely on the order in which map results are returned. The order of objects returned by maps may change without
warning. Always access map elements by key.
A map key can hold the null value.
Adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with
the new entry.
Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding
distinct Map entries. Subsequently, the Map methods, including put, get, containsKey, and remove treat these keys
as distinct.
Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods, which you provide
in your classes. Uniqueness of keys of all other non-primitive types, such as sObject keys, is determined by comparing the
objects field values.
Parameterized Typing
Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable
before that variable can be used. For example, the following is legal in Apex:
Integer x = 1;
33
Enums
Lists, maps and sets are parameterized in Apex: they take any data type Apex supports for them as an argument. That data
type must be replaced with an actual data type upon construction of the list, map or set. For example:
List<String> myList = new List<String>();
Enums
An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums
are typically used to define a set of possible values that dont otherwise have a numerical order, such as the suit of a card, or a
particular season of the year. Although each value corresponds to a distinct integer value, the enum hides this implementation
so that you dont inadvertently misuse the values, such as using them to perform arithmetic. After you create an enum, variables,
method arguments, and return types can be declared of that type.
Note: Unlike Java, the enum type itself has no constructor syntax.
To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values.
For example, the following code creates an enum called Season:
public enum Season {WINTER, SPRING, SUMMER, FALL}
By creating the enum Season, you have also created a new data type called Season. You can use this new data type as you
might any other data type. For example:
Season e = Season.WINTER;
Season m(Integer x, Season e) {
if (e == Season.SUMMER) return e;
//...
}
You can also define a class as an enum. Note that when you create an enum class you do not use the class keyword in the
definition.
public enum MyEnumClass { X, Y }
You can use an enum in any place you can use another data type name. If you define a variable whose type is an enum, any
object you assign to it must be an instance of that enum class.
34
Enums
Any webService methods can use enum types as part of their signature. When this occurs, the associated WSDL file includes
definitions for the enum and its values, which can then be used by the API client.
Apex provides the following system-defined enums:
System.StatusCode
This enum corresponds to the API error code that is exposed in the WSDL document for all API operations. For example:
StatusCode.CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
StatusCode.INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY
The full list of status codes is available in the WSDL file for your organization. For more information about accessing the
WSDL file for your organization, see Downloading Salesforce WSDLs and Client Authentication Certificates in the
Salesforce online help.
System.XmlTag:
This enum returns a list of XML tags used for parsing the result XML from a webService method. For more information,
see XmlStreamReader Class.
Enum.
System.LoggingLevel:
This enum is used with the system.debug method, to specify the log level for all debug calls. For more information,
see System Class.
System.RoundingMode:
This enum is used by methods that perform mathematical operations to specify the rounding behavior for the operation,
such as the Decimal divide method and the Double round method. For more information, see Rounding Mode.
System.SoapType:
This enum is returned by the field describe result getSoapType method. For more informations, see SOAPType Enum.
System.DisplayType:
This enum is returned by the field describe result getType method. For more information, see DisplayType Enum.
System.JSONToken:
This enum is used for parsing JSON content. For more information, see JSONToken Enum.
ApexPages.Severity:
This enum specifies the severity of a Visualforce message. For more information, see ApexPages.Severity Enum.
Dom.XmlNodeType:
All enum values, including system enums, have common methods associated with them. For more information, see Enum
Methods.
35
Variables
Variables
Local variables are declared with Java-style syntax. For example:
Integer i = 0;
String str;
List<String> strList;
Set<String> s;
Map<ID, String> m;
As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
Integer i, j, k;
Many instance methods on the data type will fail if the variable is null. In this example, the second statement generates an
exception (NullPointerException)
Date d;
d.addDays(2);
All variables are initialized to null if they arent assigned a value. For instance, in the following example, i, and k are assigned
values, while the integer variable j and the boolean variable b are set to null because they arent explicitly initialized.
Integer i = 0, j, k = 1;
Boolean b;
Note: A common pitfall is to assume that an uninitialized boolean variable is initialized to false by the system.
This isnt the case. Like all other variables, boolean variables are null if not assigned a value explicitly.
Variable Scope
Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks cant redefine a variable
name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:
Integer i;
{
// Integer i;
}
36
Constants
Case Sensitivity
To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means:
Note: Youll learn more about sObjects, SOQL and SOSL later in this guide.
Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the SOAP API and
the Salesforce user interface. The use of these semantics can lead to some interesting behavior. For example, if an end-user
generates a report based on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned
in the result. The rationale for this behavior is that users typically think of a field without a value as just a space character,
rather than its actual null value. Consequently, in Apex, the following expressions all evaluate to true:
String s;
System.assert('a' == 'A');
System.assert(s < 'b');
System.assert(!(s > 'b'));
Note: Although s < 'b' evaluates to true in the example above, 'b.'compareTo(s) generates an error because
youre trying to compare a letter to a null value.
Constants
Apex constants are variables whose values dont change after being initialized once.
Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in
the declaration itself, or with a static initializer method if the constant is defined in a class. This example declares two constants.
The first is initialized in the declaration statement. The second is assigned a value in a static block by calling a static method.
public class myCls {
static final Integer PRIVATE_INT_CONST = 200;
static final Integer PRIVATE_INT_CONST2;
public static Integer calculate() {
return 2 + 7;
}
static {
PRIVATE_INT_CONST2 = calculate();
37
}
}
For more information, see Using the final Keyword on page 74.
Understanding Expressions
Understanding Expression Operators
Understanding Operator Precedence
Expanding sObject and List Expressions
Using Comments
Understanding Expressions
An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. In Apex,
an expression is always one of the following types:
Account(<field_initializers>)
Integer[<n>]
Account[]{<elements>}
List<Account>()
Set<String>{}
Map<String, Integer>()
myRenamingClass(string oldName, string newName)
Any value that can act as the left-hand of an assignment operator (L-values), including variables, one-dimensional list
positions, and most sObject or Apex object field references. For example:
Integer i
myList[3]
myContact.name
myRenamingClass.oldName
38
A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example:
System.assert(true)
myRenamingClass.replaceNames()
changePoint(new Point(x, y));
Syntax
Description
x = y
+=
x += y
*=
x *= y
-=
x -= y
/=
x /= y
|=
x |= y
39
Operator
Syntax
Description
&=
x &= y
<<=
x <<= y
Bitwise shift left assignment operator. Shifts each bit in x to the left by y
bits so that the high order bits are lost, and the new right bits are set to 0.
This value is then reassigned to x.
>>=
x >>= y
Bitwise shift right signed assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for positive values of y and 1 for negative values of y. This value is then
reassigned to x.
>>>=
x >>>= y
Bitwise shift right unsigned assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for all values of y. This value is then reassigned to x.
? :
x ? y : z
&&
x && y
||
x || y
40
Operator
Syntax
Description
==
x == y
For sObjects and sObject arrays, == performs a deep check of all sObject
field values before returning its result. Likewise for collections and built-in
Apex objects.
For records, every field must have the same value for == to evaluate to
true.
x or y can be the literal null.
The comparison of any two values can never result in null.
SOQL and SOSL use = for their equality operator, and not ==. Although
Apex and SOQL and SOSL are strongly linked, this unfortunate syntax
discrepancy exists because most modern languages use = for assignment
and == for equality. The designers of Apex deemed it more valuable to
maintain this paradigm than to force developers to learn a new assignment
operator. The result is that Apex developers must use == for equality tests
in the main body of the Apex code, and = for equality in SOQL and SOSL
queries.
===
x === y
<
x < y
Unlike other database stored procedures, Apex does not support tri-state
Boolean logic, and the comparison of any two values can never result in
null.
If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
41
Operator
Syntax
Description
>
x > y
<=
x <= y
>=
x >= y
Operator
Syntax
Description
!=
x != y
Inequality operator. If the value of x does not equal the value of y, the
expression evaluates to true. Otherwise, the expression evaluates to false.
Note:
!==
x !== y
Exact inequality operator. If x and y do not reference the exact same location
in memory, the expression evaluates to true. Otherwise, the expression evaluates
to false.
x + y
x - y
x * y
43
Operator
Syntax
Description
x / y
!x
-x
++
x++
++x
--
x---x
&
x & y
Bitwise AND operator. ANDs each bit in x with the corresponding bit in y
so that the result bit is set to 1 if both of the bits are set to 1. This operator
is not valid for types Long or Integer.
x | y
x ^ y
^=
x ^= y
<<
x << y
Bitwise shift left operator. Shifts each bit in x to the left by y bits so that the
high order bits are lost, and the new right bits are set to 0.
>>
x >> y
Bitwise shift right signed operator. Shifts each bit in x to the right by y bits
so that the low order bits are lost, and the new left bits are set to 0 for positive
values of y and 1 for negative values of y.
>>>
x >>> y
Bitwise shift right unsigned operator. Shifts each bit in x to the right by y
bits so that the low order bits are lost, and the new left bits are set to 0 for all
values of y.
()
(x)
Using Comments
Precedence
Operators
Description
{} () ++ --
! -x +x (type) new
* /
+ -
== !=
&&
Logical AND
||
Logical OR
= += -= *= /= &=
Assignment operators
Using Comments
Both single and multiline comments are supported in Apex code:
To create a single line comment, use //. All characters on the same line to the right of the // are ignored by the parser.
For example:
Integer i = 1; // This comment is ignored by the parser
To create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. For example:
Integer i = 1; /* This comment can wrap over multiple
lines without getting interpreted by the
parser. */
Assignment Statements
An assignment statement is any statement that places a value into a variable, generally in one of the following two forms:
[LValue] = [new_value_expression];
[LValue] = [[inline_soql_query]];
In the forms above, [LValue] stands for any expression that can be placed on the left side of an assignment operator. These
include:
45
An sObject field reference that the context user has permission to edit. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
// IDs cannot be set prior to an insert call
// a.Id = '00300000003T2PGAA0';
// Instead, insert the record. The system automatically assigns it an ID.
insert a;
// Fields also must be writeable for the context user
// a.CreatedDate = System.today(); This code is invalid because
//
createdDate is read-only!
// Since the account a has been inserted, it is now possible to
// create a new contact that is related to it
Contact c = new Contact(LastName = 'Roth', Account = a);
// Notice that you can write to the account name directly through the contact
c.Account.Name = 'salesforce.com';
Similarly, two lists can point at the same value in memory. For example:
Account[] a = new Account[]{new Account()};
Account[] b = a;
a[0].Name = 'Acme';
System.assert(b[0].Name == 'Acme');
In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Understanding Expression
Operators on page 39.
1.
2.
3.
4.
Integer
Long
Double
Decimal
Note: Once a value has been passed from a number of a lower type to a number of a higher type, the value is converted
to the higher type of number.
Note that the hierarchy and implicit conversion is unlike the Java hierarchy of numbers, where the base interface number is
used and implicit object conversion is never allowed.
In addition to numbers, other data types can be implicitly converted. The following rules apply:
47
Chapter 5
Control Flow Statements
In this chapter ...
Statements are generally executed line by line, in the order they appear. With
control flow statements, you can cause Apex code to execute based on a certain
condition or you can have a block of code execute repeatedly. This section
describes these control flow statements: if-else statements and loops.
48
The else portion is always optional, and always groups with the closest if. For example:
Integer x, sign;
// Your code
if (x <= 0) if (x == 0) sign = 0; else sign = -1;
is equivalent to:
Integer x, sign;
// Your code
if (x <= 0) {
if (x == 0) {
sign = 0;
} else {
sign = -1;
}
}
Loops
Apex supports the following five types of procedural loops:
49
Do-While Loops
Do-While Loops
The Apex do-while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
do {
code_block
} while (condition);
As in Java, the Apex do-while loop does not check the Boolean condition statement until after the first loop is executed.
Consequently, the code block always runs at least once.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
do {
System.debug(count);
count++;
} while (count < 11);
While Loops
The Apex while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
while (condition) {
code_block
}
Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.
Unlike do-while, the while loop checks the Boolean condition statement before the first loop is executed. Consequently,
it is possible for the code block to never execute.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
while (count < 11) {
System.debug(count);
count++;
}
For Loops
Apex supports three variations of the for loop:
50
For Loops
or
for (variable_list : [soql_query]) {
code_block
}
Both variable and variable_list must be of the same sObject type as is returned by the soql_query.
Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.
When executing this type of for loop, the Apex runtime engine performs the following steps, in order:
1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this
statement.
2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits.
3. Execute the code_block.
4. Execute the increment_stmt statement.
5. Return to Step 2.
51
For Loops
As an example, the following code outputs the numbers 1 - 10 into the debug log. Note that an additional initialization variable,
j, is included to demonstrate the syntax:
for (Integer i = 0, j = 0; i < 10; i++) {
System.debug(i+1);
}
Iterating Collections
Collections can consist of lists, sets, or maps. Modifying a collection's elements while iterating through that collection is not
supported and causes an error. Do not directly add or remove elements while iterating through the collection that includes
them.
Adding Elements During Iteration
To add elements while iterating a list, set or map, keep the new elements in a temporary list, set, or map and add them to the
original after you finish iterating the collection.
Removing Elements During Iteration
To remove elements while iterating a list, create a new list, then copy the elements you wish to keep. Alternatively, add the
elements you wish to remove to a temporary list and remove them after you finish iterating the collection.
Note:
The List.remove method performs linearly. Using it to remove elements has time and resource implications.
To remove elements while iterating a map or set, keep the keys you wish to remove in a temporary list, then remove them
after you finish iterating the collection.
52
Chapter 6
Classes, Objects, and Interfaces
In this chapter ...
Understanding Classes
Understanding Interfaces
Keywords
Annotations
Classes and Casting
Differences Between Apex Classes and
Java Classes
Class Definition Creation
Namespace Prefix
Apex Code Versions
Lists of Custom Types and Sorting
Using Custom Types in Map Keys and
Sets
This chapter covers classes and interfaces in Apex. It describes defining classes,
instantiating them, and extending them. Interfaces, Apex class versions,
properties, and other related class concepts are also described.
In most cases, the class concepts described here are modeled on their
counterparts in Java, and can be quickly understood by those who are familiar
with them.
53
Understanding Classes
Understanding Classes
As in Java, you can create classes in Apex. A class is a template or blueprint from which objects are created. An object is an
instance of a class. For example, the PurchaseOrder class describes an entire purchase order, and everything that you can
do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive.
All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. The state
of a PurchaseOrder objectwhat it knowsincludes the user who sent it, the date and time it was created, and whether it
was flagged as important. The behavior of a PurchaseOrder objectwhat it can doincludes checking inventory, shipping
a product, or notifying a customer.
A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or
Type. Since these variables are associated with a class and are members of it, they are commonly referred to as member variables.
Methods are used to control behavior, such as getOtherQuotes or copyLineItems.
A class can contain other classes, exception types, and initialization code.
An interface is like a class in which none of the methods have been implementedthe method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
For more general information on classes, objects, and interfaces, see
http://java.sun.com/docs/books/tutorial/java/concepts/index.html
You must use one of the access modifiers (such as public or global) in the declaration of a top-level class.
You do not have to use an access modifier in the declaration of an inner class.
54
Class Variables
The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the
default access for inner classesthat is, if you don't specify an access modifier for an inner class, it is considered private.
This keyword can only be used with inner classes.
The public access modifier declares that this class is visible in your application or namespace.
The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods
defined with the webService keyword must be declared as global. If a method or inner class is declared as global,
the outer, top-level class must also be defined as global.
The with sharing and without sharing keywords specify the sharing mode for this class. For more information,
see Using the with sharing or without sharing Keywords on page 77.
The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method
with the override keyword unless the class has been defined as virtual.
The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their
signature declared and no body defined.
Note:
You cannot add an abstract method to a global class after the class has been uploaded in a Managed - Released
package version.
If the class in the Managed - Released package is virtual, the method that you can add to it must also be virtual
and must have an implementation.
You cannot override a public or protected virtual method of a global class of an installed managed package.
For more information about managed packages, see What is a Package? on page 415.
A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support
multiple inheritance. The interface names in the list are separated by commas. For more information about interfaces, see
Understanding Interfaces on page 70.
For more information about method and variable access modifiers, see Access Modifiers on page 59.
Class Variables
To declare a variable, specify the following:
55
Class Methods
For example:
private static final Integer MY_INT;
private final Integer i = 1;
Class Methods
To define a method, specify the following:
Note: You can only use override to override methods in classes that have been defined as virtual.
For example:
public static Integer getInt() {
return MY_INT;
}
As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable.
Note that user-defined methods:
56
Class Methods
Note: If the parser finds multiple approximate matches, a parse-time exception is generated.
When using void methods that have side effects, user-defined methods are typically executed as stand-alone procedure
statements in Apex code. For example:
System.debug('Here is a note for the log.');
Can have statements where the return values are run as a statement if their results are not assigned to another variable.
This is the same as in Java.
57
Using Constructors
Using Constructors
A constructor is code that is invoked when an object is created from the class blueprint. You do not need to write a constructor
for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return
type and it is not inherited by the object created from it.
After you write the constructor for a class, you must use the new keyword in order to instantiate an object from that class,
using that constructor. For example, using the following class:
public class TestObject {
// The no argument constructor
public TestObject() {
// more code here
}
}
A new object of this type can be instantiated with the following code:
TestObject myTest = new TestObject();
If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments.
If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one
in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor.
You must create your own.
58
Access Modifiers
In Apex, a constructor can be overloaded, that is, there can be more than one constructor for a class, each having different
parameters. The following example illustrates a class with two constructors: one with no arguments and one that takes a simple
Integer argument. It also illustrates how one constructor calls another constructor using the this(...) syntax, also know as
constructor chaining.
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
}
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;
}
}
New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(42);
TestObject2 myObject2 = new TestObject2();
Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors
are possible:
public class Leads {
// First a no-argument constructor
public Leads () {}
// A constructor with one argument
public Leads (Boolean call) {}
// A constructor with two arguments
public Leads (String email, Boolean call) {}
// Though this constructor has the same arguments as the
// one above, they are in a different order, so this is legal
public Leads (Boolean call, String email) {}
}
When you define a new class, you are defining a new data type. You can use class name in any place you can use other data
type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must
be an instance of that class or subclass.
Access Modifiers
Apex allows you to use the private, protected, public, and global access modifiers when defining methods and
variables.
While triggers and anonymous blocks can also use these access modifiers, they are not as useful in smaller portions of Apex.
For example, declaring a method as global in an anonymous block does not enable you to call it from outside of that code.
For more information on class access modifiers, see Apex Class Definition on page 54.
59
Note: Interface methods have no access modifiers. They are always global. For more information, see Understanding
Interfaces on page 70.
By default, a method or variable is visible only to the Apex code within the defining class. You must explicitly specify a method
or variable as public in order for it to be available to other classes in the same application namespace (see Namespace Prefix).
You can change the level of visibility by using the following access modifiers:
private
This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined.
If you do not specify an access modifier, the method or variable is private.
protected
This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that
extend the defining Apex class. You can only use this access modifier for instance methods and member variables. Note
that it is strictly more permissive than the default (private) setting, just like Java.
public
This means the method or variable can be used by any Apex in this application or namespace.
Note: In Apex, the public access modifier is not the same as it is in Java. This was done to discourage joining
applications, to keep the code for each application separate. In Apex, if you want to make something public like
it is in Java, you need to use the global access modifier.
global
This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in
the same application. This access modifier should be used for any method that needs to be referenced outside of the
application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must
also declare the class that contains it as global.
Note: We recommend using the global access modifier rarely, if at all. Cross-application dependencies are
difficult to maintain.
To use the private, protected, public, or global access modifiers, use the following syntax:
[(none)|private|protected|public|global] declaration
For example:
private string s1 = '1';
public string gets1() {
return this.s1;
}
60
Static methods, variables, or initialization code are associated with a class, and are only allowed in outer classes. When you
declare a method or variable as static, it's initialized only once when a class is loaded. Static variables aren't transmitted
as part of the view state for a Visualforce page.
Instance methods, member variables, and initialization code are associated with a particular object and have no definition
modifier. When you declare instance methods, member variables, or initialization code, an instance of that item is created
with every object instantiated from the class.
Local variables are associated with the block of code in which they are declared. All local variables should be initialized
before they are used.
The following is an example of a local variable whose scope is the duration of the if code block:
Boolean myCondition = true;
if (myCondition) {
integer localVariable = 10;
}
A trigger that uses this class could then selectively fail the first run of the trigger:
trigger t1 on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}
Static variables defined in a trigger dont retain their values between different trigger contexts within the same transaction, for
example, between before insert and after insert invocations. Define the static variables in a class instead so that the trigger can
access these class member variables and check their static values.
Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an
instance of C, then x.S is not a legal expression.
61
The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to
those static identifiers using the class: C.S and C.M().
If a local variable is named the same as the class name, these static methods and variables are hidden.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword).
Note: For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the
chunk of 200 records to process is further split into chunks of 100 records. For Apex saved using Salesforce.com API
version 21.0 and later, no further splits of API chunks occur. Note that static variable values are reset between API
batches, but governor limits are not. Do not use static variables to track state information between API batches.
Using Instance Methods and Variables
Instance methods and member variables are used by an instance of a class, that is, by an object. Instance member variables are
declared inside a class, but not within a method. Instance methods usually use instance member variables to affect the behavior
of the method.
Suppose you wanted to have a class that collects two dimensional points and plot them on a graph. The following skeleton
class illustrates this, making use of member variables to hold the list of points and an inner class to manage the two-dimensional
list of points.
public class Plotter {
// This inner class manages the points
class Point {
Double x;
Double y;
Point(Double x, Double y) {
this.x = x;
this.y = y;
}
Double getXCoordinate() {
return x;
}
Double getYCoordinate() {
return y;
}
}
List<Point> points = new List<Point>();
public void plot(Double x, Double y) {
points.add(new Point(x, y));
}
// The following method takes the list of points and does something with them
public void render() {
}
}
62
Apex Properties
The instance initialization code in a class is executed every time an object is instantiated from that class. These code blocks
run before the constructor.
If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize
instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor
to do initialization and not use instance initialization code.
Static initialization code is a block of code preceded with the keyword static:
static {
//code body
}
Similar to other static code, a static initialization code block is only initialized once on the first use of the class.
A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body.
The code blocks are executed in the order in which they appear in the file, the same as in Java.
You can use static initialization code to initialize static final variables and to declare any information that is static, such as a
map of values. For example:
public class MyClass {
class RGB {
Integer red;
Integer green;
Integer blue;
RGB(Integer red, Integer green, Integer blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
}
static Map<String, RGB> colorMap = new Map<String, RGB>();
static {
colorMap.put('red', new RGB(255, 0, 0));
colorMap.put('cyan', new RGB(0, 255, 255));
colorMap.put('magenta', new RGB(255, 0, 255));
}
}
Apex Properties
An Apex property is similar to a variable, however, you can do additional things in your code to a property value before it is
accessed or returned. Properties can be used in many different ways: they can validate data before a change is made; they can
prompt an action when data is changed, such as altering the value of other member variables; or they can expose data that is
retrieved from some other source, such as another class.
Property definitions include one or two code blocks, representing a get accessor and a set accessor:
A property with only a get accessor is considered read-only. A property with only a set accessor is considered write-only. A
property with both accessors is read-write.
63
Apex Properties
Where:
access_modifier is the access modifier for the property. The access modifiers that can be applied to properties include:
public, private, global, and protected. In addition, these definition modifiers can be applied: static and
transient. For more information on access modifiers, see Access Modifiers on page 59.
return_type is the type of the property, such as Integer, Double, sObject, and so on. For more information, see Data
For example, the following class defines a property named prop. The property is public. The property returns an integer data
type.
public class BasicProperty {
public integer prop {
get { return prop; }
set { prop = value; }
}
}
The following code segment calls the class above, exercising the get and set accessors:
BasicProperty bp = new BasicProperty();
bp.prop = 5;
// Calls set accessor
System.assert(bp.prop == 5);
// Calls get accessor
The body of the get accessor is similar to that of a method. It must return a value of the property type. Executing the get
accessor is the same as reading the value of the variable.
The get accessor must end in a return statement.
We recommend that your get accessor should not change the state of the object that it is defined on.
The set accessor is similar to a method whose return type is void.
When you assign a value to the property, the set accessor is invoked with an argument that provides the new value.
When the set accessor is invoked, the system passes an implicit argument to the setter called value of the same data type
as the property.
Properties cannot be defined on interface.
Apex properties are based on their counterparts in C#, with the following differences:
Properties provide storage for values directly. You do not need to create supporting members for storing values.
It is possible to create automatic properties in Apex. For more information, see Using Automatic Properties on page
65.
64
Apex Properties
The following code segment calls the static and instance properties:
StaticProperty sp = new StaticProperty();
// The following produces a system error: a static variable cannot be
// accessed through an object instance
// sp.MyGoodStaticProp = 5;
// The following does not produce an error
StaticProperty.MyGoodStaticProp = 5;
65
Extending a Class
Extending a Class
You can extend a class to provide a more specialized behavior.
A class that extends another class inherits all the methods and properties of the extended class. In addition, the extending class
can override the existing virtual methods by using the override keyword in the method definition. Overriding a virtual method
allows you to provide a different implementation for an existing method. This means that the behavior of a particular method
is different based on the object youre calling it on. This is referred to as polymorphism.
A class extends another class using the extends keyword in the class definition. A class can only extend one other class, but
it can implement more than one interface.
This example shows how to extend a class. The YellowMarker class extends the Marker class.
public virtual class Marker {
public virtual void write() {
System.debug('Writing some text.');
}
public virtual Double discount() {
return .05;
}
}
// Extension for the Marker class
public class YellowMarker extends Marker {
public override void write() {
System.debug('Writing some text using the yellow marker.');
}
}
This code segment shows polymorphism. The example declares two objects of the same type (Marker). Even though both
objects are markers, the second object is assigned to an instance of the YellowMarker class. Hence, calling the write method
on it yields a different result than calling this method on the first object because this method has been overridden. Note that
we can call the discount method on the second object even though this method isnt part of the YellowMarker class
definition, but it is part of the extended class, and hence is available to the extending class, YellowMarker.
Marker obj1, obj2;
obj1 = new Marker();
// This outputs 'Writing some text.'
obj1.write();
obj2 = new YellowMarker();
// This outputs 'Writing some text using the yellow marker.'
obj2.write();
// We get the discount method for free
// and can call it from the YellowMarker instance.
Double d = obj2.discount();
66
The extending class can have more method definitions that arent common with the original extended class. For example, the
RedMarker class below extends the Marker class and has one extra method, computePrice, that isnt available for the
Marker class. To call the extra methods, the object type must be the extending class.
// Extension for the Marker class
public class RedMarker extends Marker {
public override void write() {
System.debug('Writing some text in red.');
}
// Method only in this class
public Double computePrice() {
return 1.5;
}
}
This shows how to call the additional method on the RedMarker class.
RedMarker obj = new RedMarker();
// Call method specific to RedMarker only
Double price = obj.computePrice();
Extensions also apply to interfacesan interface can extend another interface. As with classes, when an interface extends
another interface, all the methods and properties of the extended interface are available to the extending interface.
67
// Inner interface
public virtual interface MyInterface {
// No access modifier is necessary for interface methods - these are always
// public or global depending on the interface visibility
void myMethod();
}
// Interface extension
interface MySecondInterface extends MyInterface {
Integer method2(Integer i);
}
// Inner class - because it is virtual it can be extended.
// This class implements an interface that, in turn, extends another interface.
// Consequently the class must implement all methods.
public virtual class InnerClass implements MySecondInterface {
// Inner member variables
private final String s;
private final String s2;
// Inner instance initialization block (this code could be located above)
{
this.s = 'x';
}
// Inline initialization (happens after the block above executes)
private final Integer i = s.length();
// Explicit no argument constructor
InnerClass() {
// This invokes another constructor that is defined later
this('none');
}
// Constructor that assigns a final variable value
public InnerClass(String s2) {
this.s2 = s2;
}
// Instance method that implements a method from MyInterface.
// Because it is declared virtual it can be overridden by a subclass.
public virtual void myMethod() { /* does nothing */ }
// Implementation of the second interface method above.
// This method references member variables (with and without the "this" prefix)
public Integer method2(Integer i) { return this.i + s.length(); }
}
// Abstract class (that subclasses the class above). No constructor is needed since
// parent class has a no-argument constructor
public abstract class AbstractChildClass extends InnerClass {
// Override the parent class method with this signature.
// Must use the override keyword
public override void myMethod() { /* do something else */ }
// Same name as parent class method, but different signature.
// This is a different method (displaying polymorphism) so it does not need
// to use the override keyword
protected void method2() {}
// Abstract method - subclasses of this class must implement this method
abstract Integer abstractMethod();
}
// Complete the abstract class by implementing its abstract method
public class ConcreteChildClass extends AbstractChildClass {
68
// Here we expand the visibility of the parent method - note that visibility
// cannot be restricted by a sub-class
public override Integer abstractMethod() { return 5; }
}
// A second sub-class of the original InnerClass
public class AnotherChildClass extends InnerClass {
AnotherChildClass(String s) {
// Explicitly invoke a different super constructor than one with no arguments
super(s);
}
}
// Exception inner class
public virtual class MyException extends Exception {
// Exception class member variable
public Double d;
// Exception class constructor
MyException(Double d) {
this.d = d;
}
// Exception class method, marked as protected
protected void doIt() {}
}
// Exception classes can be abstract and implement interfaces
public abstract class MySecondException extends Exception implements MyInterface {
}
}
69
Understanding Interfaces
This example shows how the class above can be called by other Apex code:
// Construct an instance of an inner concrete class, with a user-defined constructor
OuterClass.InnerClass ic = new OuterClass.InnerClass('x');
// Call user-defined methods in the class
System.assertEquals(2, ic.method2(1));
// Define a variable with an interface data type, and assign it a value that is of
// a type that implements that interface
OuterClass.MyInterface mi = ic;
// Use instanceof and casting as usual
OuterClass.InnerClass ic2 = mi instanceof OuterClass.InnerClass ?
(OuterClass.InnerClass)mi : null;
System.assert(ic2 != null);
// Construct the outer type
OuterClass o = new OuterClass();
System.assertEquals(2, OuterClass.getInt());
// Construct instances of abstract class children
System.assertEquals(5, new OuterClass.ConcreteChildClass().abstractMethod());
// Illegal - cannot construct an abstract class
// new OuterClass.AbstractChildClass();
// Illegal cannot access a static method through an instance
// o.getInt();
// Illegal - cannot call protected method externally
// new OuterClass.ConcreteChildClass().method2();
Understanding Interfaces
An interface is like a class in which none of the methods have been implementedthe method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the
declaration for that method. This way you can have different implementations of a method based on your specific application.
Defining an interface is similar to defining a new class. For example, a company might have two types of purchase orders,
ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you
needed a method to provide a discount. The amount of the discount can depend on the type of purchase order.
You can model the general concept of a purchase order as an interface and have specific implementations for customers and
employees. In the following example the focus is only on the discount aspect of a purchase order.
70
Custom Iterators
This class implements the PurchaseOrder interface for customer purchase orders.
// One implementation of the interface for customers
public class CustomerPurchaseOrder implements PurchaseOrder {
public Double discount() {
return .05; // Flat 5% discount
}
}
This class implements the PurchaseOrder interface for employee purchase orders.
// Another implementation of the interface for employees
public class EmployeePurchaseOrder implements PurchaseOrder {
public Double discount() {
return .10; // Its worth it being an employee! 10% discount
}
}
The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access
modifiers and contain just their signature.
The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount
method. As with Java, any class that implements an interface must define all of the methods contained in the interface.
When you define a new interface, you are defining a new data type. You can use an interface name in any place you can use
another data type name. If you define a variable whose type is an interface, any object you assign to it must be an instance of
a class that implements the interface, or a sub-interface data type.
See also Classes and Casting on page 86.
Note: You cannot add a method to a global interface after the class has been uploaded in a Managed - Released
package version.
Custom Iterators
An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for
exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. In the following example,
count is incremented by 1 every time the loop is executed (count++) :
while (count < 11) {
System.debug(count);
count++;
}
71
Custom Iterators
Using the Iterator interface you can create a custom set of instructions for traversing a List through a loop. This is useful
for data that exists in sources outside of Salesforce that you would normally define the scope of using a SELECT statement.
Iterators can also be used if you have multiple SELECT statements.
Using Custom Iterators
To use custom iterators, you must create an Apex class that implements the Iterator interface.
The Iterator interface has the following instance methods:
Name
Arguments
Returns
Description
hasNext
Boolean
next
Any type
Arguments
iterator
Returns
Description
Iterator class
The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use
to traverse the data structure.
In the following example a custom iterator iterates through a collection:
global class CustomIterable
implements Iterator<Account>{
List<Account> accs {get; set;}
Integer i {get; set;}
public CustomIterable(){
accs =
[SELECT Id, Name,
NumberOfEmployees
FROM Account
WHERE Name = 'false'];
i = 0;
}
72
Keywords
Keywords
Apex has the following keywords available:
final
instanceof
super
this
transient
with sharing and without sharing
73
Final variables can only be assigned a value once, either when you declare a variable or in initialization code. You must
assign a value to it in one of these two places.
Static final variables can be changed in static initialization code or where defined.
Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations.
To define a constant, mark a variable as both static and final.
Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they
are not shared across requests.
Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This
means they cannot be overridden. Use the virtual keyword if you need to override a method or class.
74
You can create the following class that extends Superclass and overrides its printName method:
public class Subclass extends Superclass {
public override void printName() {
super.printName();
System.debug('But you can call me ' + super.getFirstName());
}
}
The expected output when calling Subclass.printName is My name is Mr. Vonderburg. But you can call
me Carl.
You can also use super to call constructors. Add the following constructor to SubClass:
public Subclass() {
super('Madam', 'Brenda', 'Clapentrap');
}
Now, the expected output of Subclass.printName is My name is Madam Clapentrap. But you can call
me Brenda.
Best Practices for Using the super Keyword
Only classes that are extending from virtual or abstract classes can use super.
You can only use super in methods that are designated with the override keyword.
In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable
using the this keyword.
75
Or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this
format, use the this keyword with parentheses. For example:
public class testThis {
// First constructor for the class. It requires a string parameter.
public testThis(string s2) {
}
// Second constructor for the class. It does not require a parameter.
// This constructor calls the first constructor using the this keyword.
public testThis() {
this('None');
}
}
When you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor.
You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions,
or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that
define the types of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a
Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and
would use too many system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view
state. These objects include the following:
PageReferences
XmlStream classes
Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient,
such as a collection of Savepoints
Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
JSONParser class instances.
Static variables also don't get transmitted through the view state.
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page
causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date
continues to have its original value, which has been deserialized from the view state, so it remains the same.
<apex:page controller="ExampleController">
T1: {!t1} <br/>
T2: {!t2} <br/>
<apex:form>
<apex:commandLink value="refresh"/>
76
</apex:form>
</apex:page>
public class ExampleController {
DateTime t1;
transient DateTime t2;
public String getT1() {
if (t1 == null) t1 = System.now();
return '' + t1;
}
public String getT2() {
if (t2 == null) t2 = System.now();
return '' + t2;
}
}
See Also:
JSONParser Class
Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not
enforced. For example:
public without sharing class noSharing {
// Code here
}
77
Annotations
The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For
example, if a method is defined in a class declared with with sharing is called by a class declared with without
sharing, the method will execute with sharing rules enforced.
If a class isnt declared as either with or without sharing, the current sharing rules remain in effect. This means that if the
class is called by a class that has sharing enforced, then sharing is enforced for the called class.
Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained
in the class, including initialization code, constructors, and methods.
Inner classes do not inherit the sharing setting from their container class.
Classes inherit this setting from a parent class when one class extends or implements another.
Annotations
An Apex annotation modifies the way a method or class is used, similar to annotations in Java.
Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To add an annotation to a method,
specify it immediately before the method or class definition. For example:
@Deprecated
@Future
@IsTest
@ReadOnly
@RemoteAction
@TestVisible
@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut
Deprecated Annotation
Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer
be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring
code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements
continue to function for existing subscribers and API integrations.
78
Future Annotation
The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums,
interfaces, or variables.
@deprecated
// This method is deprecated. Use myOptimizedMethod(String a, String b) instead.
global void myMethod(String a) {
}
Unmanaged packages cannot contain code that uses the deprecated keyword.
When an Apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be
deprecated. Any global method that uses the deprecated type in its signature, either in an input argument or the method
return type, must also be deprecated. A deprecated item, such as a method or a class, can still be referenced internally by
the package developer.
webService methods and variables cannot be deprecated.
You can deprecate an enum but you cannot deprecate individual enum values.
You can deprecate an interface but you cannot deprecate individual methods in an interface.
You can deprecate an abstract class but you cannot deprecate individual abstract methods in an abstract class.
You cannot remove the deprecated annotation to undeprecate something in Apex after you have released a package
version where that item in Apex is deprecated.
For more information about package versions, see What is a Package? on page 415.
Future Annotation
Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method
executes when Salesforce has available resources.
For example, you can use the future annotation when making an asynchronous Web service callout to an external service.
Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no
additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type. The specified parameters must
be primitive data types, arrays of primitive data types, or collections of primitive data types. Methods with the future
annotation cannot take sObjects or objects as arguments.
To make a method in a class execute asynchronously, define the method with the future annotation. For example:
global class MyFutureClass {
@future
static void myMethod(String a, Integer i) {
System.debug('Method called with: ' + a + ' and ' + i);
// Perform long-running code
}
}
Specify (callout=true) to allow callouts in a future method. Specify (callout=false) to prevent a method from making
callouts.
79
IsTest Annotation
The following snippet shows how to specify that a method executes a callout:
@future (callout=true)
public static void doCalloutFromFuture() {
//Add code to perform callout
}
Remember that any method using the future annotation requires special consideration because the method does not
necessarily execute in the same order it is called.
Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or
setMethodName methods, nor in the constructor.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call
a trigger from an annotated method that calls another annotated method.
The getContent and getContentAsPDF PageReference methods cannot be used in methods with the future
annotation.
IsTest Annotation
Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest
annotation on methods is equivalent to the testMethod keyword.
Note: Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex
code.
Classes and methods defined as isTest can be either private or public. Classes defined as isTest must be top-level
classes.
This is an example of a private test class that contains two test methods.
@isTest
private class MyTestClass {
// Methods for testing
@isTest static void test1() {
// Implement test code
}
@isTest static void test2() {
// Implement test code
}
}
This is an example of a public test class that contains utility methods for test data creation:
@isTest
public class TestUtil {
public static void createTestAccounts() {
// Create some test accounts
}
public static void createTestContacts() {
// Create some test contacts
}
80
IsTest Annotation
For Apex code saved using Salesforce.com API version 24.0 and later, use the isTest(SeeAllData=true) annotation to
grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test
didnt create. Starting with Apex code saved using Salesforce.com API version 24.0, test methods dont have access by default
to pre-existing data in the organization. However, test code saved against Salesforce.com API version 23.0 and earlier continues
to have access to all data in the organization and its data access is unchanged. See Isolation of Test Data from Organization
Data in Unit Tests on page 390.
Considerations for the IsTest(SeeAllData=true) Annotation
If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test
methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method
level. However, using isTest(SeeAllData=false) on a method doesnt restrict organization data access for that
method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this
case, the method will still have access to all the data in the organization.
This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in
this class have access to all data in the organization.
// All test methods in this class can access all data.
@isTest(SeeAllData=true)
public class TestDataAccessClass {
// This test accesses an existing account.
// It also creates and accesses a new test account.
static testmethod void myTestMethod1() {
// Query an existing account in the organization.
Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1];
System.assert(a != null);
// Create a test account based on the queried account.
Account testAccount = a.clone();
testAccount.Name = 'Acme Test';
insert testAccount;
// Query the test account that was inserted.
Account testAccount2 = [SELECT Id, Name FROM Account
WHERE Name='Acme Test' LIMIT 1];
System.assert(testAccount2 != null);
}
// Like the previous method, this test method can also access all data
// because the containing class is annotated with @isTest(SeeAllData=true).
@isTest static void myTestMethod2() {
// Can access all data in the organization.
}
}
81
IsTest Annotation
This second example shows how to apply the isTest(SeeAllData=true) annotation on a test method. Because the class
that the test method is contained in isnt defined with this annotation, you have to apply this annotation on the test method
to enable access to all data for that test method. The second test method doesnt have this annotation, so it can access only
the data it creates in addition to objects that are used to manage your organization, such as users.
// This class contains test methods with different data access levels.
@isTest
private class ClassWithDifferentDataAccess {
// Test method that has access to all data.
@isTest(SeeAllData=true)
static void testWithAllDataAccess() {
// Can query all data in the organization.
}
// Test method that has access to only the data it creates
// and organization setup and metadata objects.
@isTest static void testWithOwnDataAccess() {
// This method can still access the User object.
// This query returns the first user object.
User u = [SELECT UserName,Email FROM User LIMIT 1];
System.debug('UserName: ' + u.UserName);
System.debug('Email: ' + u.Email);
// Can access the test account that is created here.
Account a = new Account(Name='Test Account');
insert a;
// Access the account that was just created.
Account insertedAcct = [SELECT Id,Name FROM Account
WHERE Name='Test Account'];
System.assert(insertedAcct != null);
}
}
IsTest(OnInstall=true) Annotation
Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This
annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are
part of a test class that has this annotation, will be executed during package installation. Tests annotated to run during package
installation must pass in order for the package installation to succeed. It is no longer possible to bypass a failing test during
package installation. A test method or a class that doesn't have this annotation, or that is annotated with
isTest(OnInstall=false) or isTest, won't be executed during installation.
This example shows how to annotate a test method that will be executed during package installation. In this example, test1
will be executed but test2 and test3 won't.
public class OnInstallClass {
// Implement logic for the class.
public void method1(){
// Some code
}
}
@isTest
private class OnInstallClassTest {
// This test method will be executed
// during the installation of the package.
@isTest(OnInstall=true)
static void test1() {
// Some test code
}
// Tests excluded from running during the
82
ReadOnly Annotation
ReadOnly Annotation
The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database. All other limits still
apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks
you from performing the following operations within the request: DML operations, calls to System.schedule, calls to
methods annotated with @future, and sending emails.
The @ReadOnly annotation is available for Web services and the Schedulable interface. To use the @ReadOnly annotation,
the top level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page calls
a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top level request, not the
Web service.
Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods will run with the same
relaxed restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration
component like <apex:pageBlockTable>, you can set the readonly attribute on the <apex:page> tag to true. For
more information, see Working with Large Sets of Data in the Visualforce Developer's Guide.
RemoteAction Annotation
The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This
process is often referred to as JavaScript remoting.
Note: Methods with the RemoteAction annotation must be static and either global or public.
To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);
namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if
83
TestVisible Annotation
configuration configures the handling of the remote call and response. Use this to change the behavior of a remoting
Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces
as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have
an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes
and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference.
For more information, see JavaScript Remoting for Apex Controllers in the Visualforce Developer's Guide.
TestVisible Annotation
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the
test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive
access level for running tests only. This annotation doesnt change the visibility of members if accessed by non-test classes.
With this annotation, you dont have to change the access modifiers of your methods and member variables to public if you
want to access them in a test method. For example, if a private member variable isnt supposed to be exposed to external classes
but it should be accessible by a test method, you can add the TestVisible annotation to the variable definition.
This example shows how to annotate a private class member variable and private method with TestVisible.
public class TestVisibleExample {
// Private member variable
@TestVisible private static Integer recordNumber = 1;
// Private method
@TestVisible private static void updateRecord(String name) {
// Do something
}
}
This is the test class that uses the previous class. It contains the test method that accesses the annotated member variable and
method.
@isTest
private class TestVisibleExampleTest {
@isTest static void test1() {
// Access private variable annotated with TestVisible
Integer i = TestVisibleExample.recordNumber;
System.assertEquals(1, i);
// Access private method annotated with TestVisible
TestVisibleExample.updateRecord('RecordName');
// Perform some verification
}
}
84
@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut
RestResource Annotation
The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
These are some considerations when using this annotation:
URL Guidelines
URL path mappings are as follows:
The URL for a namespaced classes contains the namespace. For example, if your class is in namespace abc and the class is
mapped to your_url, then the API URL is modified as follows:
https://instance.salesforce.com/services/apexrest/abc/your_url/. In the case of a URL collision, the
namespaced class is always used.
HttpDelete Annotation
The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP DELETE request is sent, and deletes the specified resource.
To use this annotation, your Apex method must be defined as global static.
HttpGet Annotation
The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP GET request is sent, and returns the specified resource.
These are some considerations when using this annotation:
To use this annotation, your Apex method must be defined as global static.
Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method.
85
HttpPatch Annotation
The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP PATCH request is sent, and updates the specified resource.
To use this annotation, your Apex method must be defined as global static.
HttpPost Annotation
The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP POST request is sent, and creates a new resource.
To use this annotation, your Apex method must be defined as global static.
HttpPut Annotation
The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP PUT request is sent, and creates or updates the specified resource.
To use this annotation, your Apex method must be defined as global static.
The following is not legal, because the compiler does not know that what you are
returning is a custom report. You must use cast to tell it that you know what
type you are returning
CustomReport c = Reports.get(0);
// Instead, get the first item in the list by casting it back to a custom report object
CustomReport c = (CustomReport) Reports.get(0);
}
}
86
Collection Casting
Because collections in Apex have a declared type at runtime, Apex allows collection casting.
87
Collections can be cast in a similar manner that arrays can be cast in Java. For example, a list of CustomerPurchaseOrder
objects can be assigned to a list of PurchaseOrder objects if class CustomerPurchaseOrder is a child of class PurchaseOrder.
public virtual class PurchaseOrder {
Public class CustomerPurchaseOrder extends PurchaseOrder {
}
{
List<PurchaseOrder> POs = new PurchaseOrder[] {};
List<CustomerPurchaseOrder> CPOs = new CustomerPurchaseOrder[]{};
POs = CPOs;}
}
Once the CustomerPurchaseOrder list is assigned to the PurchaseOrder list variable, it can be cast back to a list of
CustomerPurchaseOrder objects, but only because that instance was originally instantiated as a list of CustomerPurchaseOrder.
A list of PurchaseOrder objects that is instantiated as such cannot be cast to a list of CustomerPurchaseOrder objects, even if
the list of PurchaseOrder objects contains only CustomerPurchaseOrder objects.
If the user of a PurchaseOrder list that only includes CustomerPurchaseOrders objects tries to insert a
non-CustomerPurchaseOrder subclass of PurchaseOrder (such as InternalPurchaseOrder), a runtime exception results.
This is because Apex collections have a declared type at runtime.
Note: Maps behave in the same way as lists with regards to the value side of the Mapif the value side of map A
can be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime
error results if the casting is not valid with the particular map at runtime.
Inner classes and interfaces can only be declared one level deep inside an outer class.
Static methods and variables can only be declared in a top-level class definition, not in an inner class.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this
keyword).
The private access modifier is the default, and means that the method or variable is accessible only within the Apex
class in which it is defined. If you do not specify an access modifier, the method or variable is private.
Specifying no access modifier for a method or variable and the private access modifier are synonymous.
The public access modifier means the method or variable can be used by any Apex in this application or namespace.
The global access modifier means the method or variable can be used by any Apex code that has access to the class, not
just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced
outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global,
you must also declare the class that contains it as global.
Methods and classes are final by default.
The virtual definition modifier allows extension and overrides.
The override keyword must be used explicitly on methods that override base class methods.
88
Exception classes have four implicit constructors that are built-in, although you can add others.
Classes and interfaces can be defined in triggers and anonymous blocks, but only as local.
See Also:
Exceptions in Apex
Naming Conventions
To make the search operation case sensitive, select the Match Case option.
To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag
with an <h2> tag and keep all the attributes on the original <h1> intact, search for <h1(\s+)(.*)> and replace it
with <h2$1$2>.
Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Undo (
) and Redo (
Use undo to reverse an editing action and redo to recreate an editing action that was undone.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used
with go to line (
Naming Conventions
We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase
verb, and variable names should be meaningful.
It is not legal to define a class and interface with the same name in the same class. It is also not legal for an inner class to have
the same name as its outer class. However, methods and variables have their own namespaces within the class so these three
types of names do not clash with each other. In particular it is legal for a variable, method, and a class within a class to have
the same name.
Name Shadowing
Member variables can be shadowed by local variablesin particular function arguments. This allows methods and constructors
of the standard Java form:
Public Class Shadow {
String s;
Shadow(String s) { this.s = s; } // Same name ok
setS(String s) { this.s = s; } // Same name ok
}
Member variables in one class can shadow member variables with the same name in a parent classes. This can be useful if the
two classes are in different top-level classes and written by different teams. For example, if one has a reference to a class C and
90
Namespace Prefix
wants to gain access to a member variable M in parent class P (with the same name as a member variable in C) the reference
should be assigned to a reference to P first.
Static variables can be shadowed across the class hierarchyso if P defines a static S, a subclass C can also declare a static S.
References to S inside C refer to that staticin order to reference the one in P, the syntax P.S must be used.
Static class variables cannot be referenced through a class instance. They must be referenced using the raw variable name by
itself (inside that top-level class file) or prefixed with the class name. For example:
public class p1 {
public static final Integer CLASS_INT = 1;
public class c { };
}
p1.c c = new p1.c();
// This is illegal
// Integer i = c.CLASS_INT;
// This is correct
Integer i = p1.CLASS_INT;
Namespace Prefix
The Salesforce application supports the use of namespace prefixes. Namespace prefixes are used in managed Force.com
AppExchange packages to differentiate custom object and field names from those in use by other organizations. After a
developer registers a globally unique namespace prefix and registers it with AppExchange registry, external references to custom
object and field names in the developer's managed packages take on the following long format:
namespace_prefix__obj_or_field_name__c
Because these fully-qualified names can be onerous to update in working SOQL statements, SOSL statements, and Apex
once a class is marked as managed, Apex supports a default namespace for schema names. When looking at identifiers, the
parser considers the namespace of the current object and then assumes that it is the namespace of all other objects and fields
unless otherwise specified. Consequently, a stored class should refer to custom object and field names directly (using
obj_or_field_name__c) for those objects that are defined within its same application namespace.
Tip: Only use namespace prefixes when referring to custom objects and fields in managed packages that have been
installed to your organization from theAppExchange.
91
And:
URL url1 = new URL('http://na1.salesforce.com');
Similarly, to call a static method on the URL class, you can write either of the following:
System.URL.getCurrentRequestUrl();
Or:
URL.getCurrentRequestUrl();
Note: In addition to the System namespace, there is a built-in System class in the System namespace, which
provides methods like assertEquals and debug. Dont get confused by the fact that both the namespace and the
class have the same name in this case. The System.debug('debug message'); and
System.System.debug('debug message'); statements are equivalent.
Using the System Namespace for Disambiguation
It is easier to not include the System namespace when calling static methods of system classes, but there are situations where
you must include the System namespace to differentiate the built-in Apex classes from custom Apex classes with the same
name. If your organization contains Apex classes that youve defined with the same name as a built-in class, the Apex runtime
defaults to your custom class and calls the methods in your class. Lets take a look at the following example.
Create this custom Apex class:
public class Database {
public static String query() {
return 'wherefore art thou namespace?';
}
}
When the Database.query statement executes, Apex looks up the query method on the custom Database class first.
However, the query method in this class doesnt take any parameters and no match is found, hence you get an error. The
custom Database class overrides the built-in Database class in the System namespace. To solve this problem, add the
System namespace prefix to the class name to explicitly instruct the Apex runtime to call the query method on the built-in
Database class in the System namespace:
sObject[] acct = System.Database.query('SELECT Name FROM Account LIMIT 1);
System.debug(acct[0].get('Name'));
2. If the first assumption does not hold true, the parser then assumes that name1 is a class name and name2 is a static variable
name with name3 - nameN as field references.
3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, and name4 - nameN are field references.
4. If the third assumption does not hold true, the parser reports an error.
If the expression ends with a set of parentheses (for example, name1.name2.[...].nameM.nameN()), the Apex parser
evaluates the expression as follows:
1. The parser first assumes that name1 is a local variable with name2 - nameM as field references, and nameN as a method
invocation.
2. If the first assumption does not hold true:
If the expression contains only two identifiers (name1.name2()), the parser then assumes that name1 is a class name
and name2 is a method invocation.
If the expression contains more than two identifiers, the parser then assumes that name1 is a class name, name2 is a
static variable name with name3 - nameM as field references, and nameN is a method invocation.
3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, name4 - nameM are field references, and nameN is a method invocation.
4. If the third assumption does not hold true, the parser reports an error.
However, with class variables Apex also uses dot notation to reference member variables. Those member variables might refer
to other class instances, or they might refer to an sObject which has its own dot notation rules to refer to field names (possibly
navigating foreign keys).
Once you enter an sObject field in the expression, the remainder of the expression stays within the sObject domain, that is,
sObject fields cannot refer back to Apex expressions.
For instance, if you have the following class:
public class c {
c1 c1 = new c1();
class c1 { c2 c2; }
class c2 { Account a; }
}
For a type reference TypeN, the parser first looks up that type as a scalar type.
If TypeN is not found, the parser looks up locally defined types.
If TypeN still is not found, the parser looks up a class of that name.
If TypeN still is not found, the parser looks up system types such as sObjects.
93
For the type T1.T2 this could mean an inner type T2 in a top-level class T1, or it could mean a top-level class T2 in the
namespace T1 (in that order of precedence).
94
If you save an Apex class or trigger that references a managed package without specifying a version of the managed package,
the Apex class or trigger is associated with the latest installed version of the managed package by default.
You cannot Remove a class or trigger's version setting for a managed package if the package is referenced in the class or
trigger. Use Show Dependencies to find where a managed package is referenced by a class or trigger.
95
Warning: If the object in your map keys or set elements changes after being added to the collection, it wont be found
anymore because of changed field values.
When using a custom type (your Apex class) for the map key or set elements, provide equals and hashCode methods in
your class. Apex uses these two methods to determine equality and uniqueness of keys for your objects.
Keep in mind the following when implementing the equals method. Assuming x, y, and z are non-null instances of your
class, the equals method must be:
Reflexive: x.equals(x)
Symmetric: x.equals(y) should return true if and only if y.equals(x) returns true
Transitive: if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
Consistent: multiple invocations of x.equals(y) consistently return true or consistently return false
For any non-null reference value x, x.equals(null) should return false
96
Sample
This sample shows how to implement the equals and hashCode methods. The class that provides those methods is listed
first. It also contains a constructor that takes two Integers. The second example is a code snippet that creates three objects of
the class, two of which have the same values. Next, map entries are added using the pair objects as keys. The sample verifies
that the map has only two entries since the entry that was added last has the same key as the first entry, and hence, overwrote
it. The sample then uses the == operator, which works as expected because the class implements equals. Also, some additional
map operations are performed, like checking whether the map contains certain keys, and writing all keys and values to the
debug log. Finally, the sample creates a set and adds the same objects to it. It verifies that the set size is two, since only two
objects out of the three are unique.
public class PairNumbers {
Integer x,y;
public PairNumbers(Integer a, Integer b) {
x=a;
y=b;
}
public Boolean equals(Object obj) {
if (obj instanceof PairNumbers) {
PairNumbers p = (PairNumbers)obj;
return ((x==p.x) && (y==p.y));
}
return false;
}
public Integer hashCode() {
return (31 * x) ^ y;
}
}
97
98
Chapter 7
Working with Data in Apex
In this chapter ...
sObject Types
Adding and Retrieving Data
DML
SOQL and SOSL Queries
SOQL For Loops
sObject Collections
Dynamic Apex
Apex Security and Sharing
Custom Settings
This chapter describes how you can add and interact with data in the Force.com
platform persistence layer. In this chapter, youll learn about the main data type
that holds data objectsthe sObject data type. Youll also learn about the
language used to manipulate dataData Manipulation Language (DML), and
query languages used to retrieve data, such as the (), among other things. This
chapter also explains the use of custom settings in Apex.
99
sObject Types
sObject Types
In this developer's guide, the term sObject refers to any object that can be stored in the Force.com platform database. An
sObject variable represents a row of data and can only be declared in Apex using the SOAP API name of the object. For
example:
Account a = new Account();
MyCustomObject__c co = new MyCustomObject__c();
Similar to the SOAP API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data
type can be used in code that processes different types of sObjects.
The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example:
sObject s = new Account();
You can also use casting between the generic sObject type and the specific sObject type. For example:
// Cast the generic variable s from the example above
// into a specific account and account variable a
Account a = (Account)s;
// The following generates a runtime error
Contact c = (Contact)s;
Because sObjects work like objects, you can also have the following:
Object obj = s;
// and
a = (Account)obj;
DML operations work on variables declared as the generic sObject data type as well as with regular sObjects.
sObject variables are initialized to null, but can be assigned a valid object reference with the new operator. For example:
Account a = new Account();
Developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sObject.
For example:
Account a = new Account(name = 'Acme', billingcity = 'San Francisco');
For information on accessing existing sObjects from the Force.com platform database, see SOQL and SOSL Queries in
the Force.com SOQL and SOSL Reference.
Note: The ID of an sObject is a read-only value and can never be modified explicitly in Apex unless it is cleared
during a clone operation, or is assigned with a constructor. The Force.com platform assigns ID values automatically
when an object record is initially inserted to the database for the first time. For more information see Lists on page
29.
100
Custom Labels
Custom labels are not standard sObjects. You cannot create a new instance of a custom label. You can only access the value
of a custom label using system.label.label_name. For example:
String errorMsg = System.Label.generic_error;
For more information on custom labels, see Custom Labels Overview in the Salesforce online help.
System generated fields, such as Created By or Last Modified Date, cannot be modified. If you try, the Apex runtime
engine generates an error. Additionally, formula field values and values for other fields that are read-only for the context user
cannot be changed.
If you use the generic sObject type instead of a specific object, such as Account, you can retrieve only the Id field using dot
notation. You can set the Id field for Apex code saved using Salesforce.com API version 27.0 and later). Alternatively, you
can use the generic sObject put and get methods. See sObject Class.
This example shows how you can access the Id field and operations that arent allowed on generic sObjects.
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
// This is allowed
ID id = s.Id;
// The following line results in an error when you try to save
String x = s.Name;
// This line results in an error when you try to save using API version 26.0 or earlier
s.Id = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1].Id;
Note: If your organization has enabled person accounts, you have two different kinds of accounts: business accounts
and person accounts. If your code creates a new account using name, a business account is created. If your code uses
LastName, a person account is created.
If you want to perform operations on an sObject, it is recommended that you first convert it into a specific object. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
ID id = s.ID;
Account convertedAccount = (Account)s;
convertedAccount.name = 'Acme2';
update convertedAccount;
Contact sal = new Contact(FirstName = 'Sal', Account = convertedAccount);
The following example shows how you can use SOSL over a set of records to determine their object types. Once you have
converted the generic sObject record into a Contact, Lead, or Account, you can modify its fields accordingly:
public class convertToCLA {
List<Contact> contacts;
101
List<Lead> leads;
List<Account> accounts;
public void convertType(Integer phoneNumber) {
List<List<sObject>> results = [FIND '4155557000'
IN Phone FIELDS
RETURNING Contact(Id, Phone, FirstName, LastName),
Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)];
sObject[] records = ((List<sObject>)results[0]);
if (!records.isEmpty()) {
for (Integer i = 0; i < records.size(); i++) {
sObject record = records[i];
if (record.getSObjectType() == Contact.sObjectType) {
contacts.add((Contact) record);
} else if (record.getSObjectType() == Lead.sObjectType){
leads.add((Lead) record);
} else if (record.getSObjectType() == Account.sObjectType) {
accounts.add((Account) record);
}
}
}
}
}
102
DML
In the previous example, the account referenced by the variable a exists in memory with the required Name field. However, it
is not persisted yet to the Force.com platform persistence layer. You need to call DML statements to persist sObjects to the
database. Here is an example of creating and persisting this account using the insert statement.
Account a = new Account(Name='Account Example');
insert a;
Also, you can use DML to modify records that have already been inserted. Among the operations you can perform are record
updates, deletions, restoring records from the Recycle Bin, merging records, or converting leads. After querying for records,
you get sObject instances that you can modify and then persist the changes of. This is an example of querying for an existing
record that has been previously persisted, updating a couple of fields on the sObject representation of this record in memory,
and then persisting this change to the database.
// Query existing account.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account Example' LIMIT 1];
// Write the old values the debug log before updating them.
System.debug('Account Name before update: ' + a.Name); // Name is Account Example
System.debug('Account Industry before update: ' + a.Industry);// Industry is not set
// Modify the two fields on the sObject.
a.Name = 'Account of the Day';
a.Industry = 'Technology';
// Persist the changes.
update a;
// Get a new copy of the account from the database with the two fields.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account of the Day' LIMIT 1];
// Verify that updated field values were persisted.
System.assertEquals('Account of the Day', a.Name);
System.assertEquals('Technology', a.Industry);
DML
DML Statements vs. Database Class Methods
Apex offers two ways to perform DML operations: using DML statements or Database class methods. This provides flexibility
in how you perform data operations. DML statements are more straightforward to use and result in exceptions that you can
handle in your code. This is an example of a DML statement to insert a new record.
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
insert acctList;
103
This is an equivalent example to the previous one but it uses a method of the Database class instead of the DML verb.
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
Database.SaveResult[] sr = Database.insert(acctList, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully inserted account. Account ID: ' + sr.getId());
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}
One difference between the two options is that by using the Database class method, you can specify whether or not to allow
for partial record processing if errors are encountered. You can do so by passing an additional second Boolean parameter. If
you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead
of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of
each operation and any errors encountered. By default, this optional parameter is true, which means that if at least one
sObject cant be processed, all remaining sObjects wont and an exception will be thrown for the record that causes a failure.
The following helps you decide when you want to use DML statements or Database class methods.
Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception
that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions
are handled in most database procedural languages.
Use Database class methods if you want to allow partial success of a bulk DML operationif a record fails, the remainder
of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the
operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use
the appropriate results array to judge success or failure. Note that Database methods also include a syntax that supports
thrown exceptions, similar to DML statements.
Note:
Most operations overlap between the two, except for a few.
The convertLead operation is only available as a Database class method, not as a DML statement.
The Database class also provides methods not available as DML statements, such as methods transaction control
and rollback, emptying the Recycle Bin, and methods related to SOQL queries.
104
All operations that occur inside the transaction boundary represent a single unit of operations. This also applies to calls that
are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running
in the transaction boundary. For example, consider the following chain of operations: a custom Apex Web service method
calls a method in a class that performs some DML operations. In this case, all changes are committed to the database only<