Is it possible to reference the fields of an sObject (opportunity in this example) dynamically from a string value?

For example, take the following code:

 for(Opportunity o: oppList) {
      for(String s : strList) {
           // I'd like to set the opportunity field values based on the string 
           // value that contains the API name of the opportunity field

So, the variable strList contains the opportunity API field names. I'm trying to clear some fields on the opportunity in a before update trigger, but I have to access the field names dynamically in the strList.

1 Answer 1


Yes, the "get" and "put" methods allow reading and writing fields by their field names:

for(Opportunity record: records) {
  for(String fieldName: fieldNames) {
    Object value = record.get(fieldName); // Get a field value!
    record.put(fieldName, null); // Clear a field!
  • Thank you @sfdcfox Worked perfectly!!
    – Dman100
    Oct 22, 2020 at 21:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .