Assign record values dynamically in Apex
Each standard and custom object inherits methods from the SObject class.
Each standard and custom object inherits methods from the SObject class.
There are two methods worth considering in the context of our tip:
apex
put(String fieldName, Object value)
put(Schema.SObjectField field, Object value)It can be very useful in Test Data Factory frameworks where values need to be overridden.
Dynamic assignment works perfectly with Maps, where the Field is a key.
apex
public void updateFields(SObject record, Map<SObjectField, Object> fieldToValue) {
for (SObjectField field : fieldToValue.keySet()) {
record.put(field, fieldToValue.get(field));
}
}so usage can look like this:
apex
updateFields(myAccount, new Map<SObjectField, Object>{
Account.Name => 'My Account',
Account.Industry => 'IT'
});apex
updateFields(myAccount, new Map<String, Object>{
'Name' => 'My Account',
'Industry' => 'IT'
});

