You need to use the
put methods. Each method supports both
SObjectField as the parameter type:
SObjectField fieldToGet = MyObject__c.ExternalId__c;
SObjectField fieldToPut = MyObject__c.UniqueId__c;
Object value = myObject.get(fieldToGet);
There are many different scenarios under which you may want to use the dynamic methods
put. How do you decide whether to use
- Creates a hard-coded reference to the field.
- If you try to delete the referenced field or change its API Name, the UI will prevent you from doing so!
- In other words, this approach protects your code.
- Syntax is somewhat more verbose. If you are really crunching up against the character limit, this style of reference might use more than you need.
- There are probably better ways to shave characters.
- You cannot pass cross-object references, like if you wanted to reference
- You cannot call
someOpportunity.get('Account.Owner.Name'), but you can combine
getSObject and some string parsing to achieve the desired result.
- More terse syntax allows you to write the same code in fewer characters.
- Accepting this type as an input for your own method would allow you to support cross-object
get calls (by incorporating
- Does not populate to the SymbolTable, meaning there is no programmatic connection anywhere between your code and the referenced field.
- Because there is no programmatic connection, the system. will allow the field to be deleted or renamed (barring other blocking dependencies).
- In other words, your code is vulnerable to configuration changes which might break it down the road.
Both of the above are well covered in the
Apex Developer Guide documentation for the
SObject class. There are a few more signatures but you get the idea:
Returns the value for the field specified by fieldName, such as AccountNumber.
public Object get(String fieldName)
For more information, see Dynamic SOQL.
Sets the value for the field specified by the field token Schema.sObjectField, such as, Schema.Account.AccountNumber and returns the previous value for the field.
public Object put(Schema.SObjectField fieldName, Object value)