Intermediate 25 min read

Dynamic sObjects

By the end of this lesson, you'll be able to:

  • Access a field by name at runtime using get() and put()
  • Explain when a dynamic field access is necessary versus dot notation
  • Use Schema-based type resolution to create an sObject when the type isn't known at compile time

Prerequisites: "What Is an sObject?"

Reading and writing a field dynamically

Account acc = new Account();
acc.put('Name', 'Acme Logistics'); // same as acc.Name = 'Acme Logistics'
System.debug(acc.get('Name'));      // same as acc.Name

put(fieldName, value) and get(fieldName) access a field using its API name as a String, rather than the fixed acc.Name dot notation. The result is identical — this is purely a different way of reading and writing the same field.

When this is actually necessary

public void updateFieldDynamically(sObject record, String fieldName, Object newValue) {
    record.put(fieldName, newValue);
}

Account acc = new Account();
updateFieldDynamically(acc, 'Industry', 'Manufacturing');

Dot notation (acc.Industry = 'Manufacturing') requires knowing the field name when the code is written. If the field name itself is only known at runtime — say, from a configuration record or a method parameter, as in updateFieldDynamically above — dynamic access is the only option, since there's no way to write acc.fieldName literally.

A real business example: Configurable Field Mapping

Map<String, Object> importedRow = new Map<String, Object>{
    'Name' => 'Riverbend Farms',
    'Industry' => 'Agriculture'
};

Account acc = new Account();
for (String fieldName : importedRow.keySet()) {
    acc.put(fieldName, importedRow.get(fieldName));
}

A data import tool that reads column names from a spreadsheet has no way to know those field names at compile time — dynamic put() is exactly what makes a genuinely reusable import routine possible, regardless of which fields a given spreadsheet happens to contain.

Exercise

Write a method getFieldValue(sObject record, String fieldName) that returns the value of the given field using dynamic access.

Show hint

return record.get(fieldName);

APEX

Dynamic sObjects Quiz

1. When is dynamic field access (get/put) necessary instead of dot notation?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Sometimes the field or object you need to work with isn't known until the code actually runs — dynamic sObject access handles this using field names as Strings instead of fixed dot notation.