SObject field access
Change records (DML) · Beginner · 8 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A reusable mapper knows some Account fields at compile time and receives other field API names dynamically.
Set and read Account fields with dot notation and dynamic SObject methods without saving a record.
What you will learn
Use dot notation when you know the field while you write the code. Use put and get when the field's API name arrives as text at run time.
account.Name = name;
account.put('Description', note);
String text = (String) account.get('Description');
put and get also accept a field token, like Account.Description.
Gotcha. get returns Object, so cast it when you need a typed value.
The task
Set and read fields on one Account in memory, using dot notation and the dynamic put and get methods.
Examples:
account.Name = name;, then readaccount.Name→Dot name: AS Field Practiceputthe Description, then read it withget→Dynamic description: Prepared in memory- fields you never set read as null →
Phone unset: trueandId unset: true
Requirements:
- Set the Account's Name with dot notation and its Description with
put. - Read Description back with
getand cast the result to String. - Do not insert the Account. It stays in memory only.
- Print
Dot name:,Dynamic description:,Phone unset:andId unset:in that order.
Starter code
String name = 'AS Field Practice';
String description = 'Prepared in memory';
Account account = new Account();
String dynamicDescription;
When it passes
The Account stays in memory, both access styles return the assigned values, and untouched fields remain null.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.