Dynamically Retrieve And Update Field as Variables

Sometimes you would like to update fields by using their field names as variables. I have found the dynamic fetching and updating of SObject fields very efficient.

I have an method that needs to update a specific User field with 4 different values. Without parsing 4 parameters and doing allot of if statement I can now get the field by it’s name and update it in one line.


SObject s = [SELECT Name FROM Account LIMIT 1];
Object o = s.get('Name');
s.put('Name', 'abc');
update s;

Now you can use it in a method


public static User updateUserRecordCount(User userToUpdateCount, String dateTimeField)
{
   userToUpdateCount.put(dateTimeField, DateTime.Now());
   return userToUpdateCount;
}