0

I am trying to access the value of a field on a custom object dynamically. e.g. customObject__c currently doesn't have customField1__c on it. It will be created in the future. Is there a way that I can use this name and value (I know the name of the field but not value. Value will be given in the future when it will be created) in the apex code?

for(customObject__c co:lstCustomobjects){
   String str;
   str = co.customField1__c; //currently if I try this, I get error variable doesn't exists - customField1__c which is understandable
   system.debug(str); 
}

1 Answer 1

1

You can use dynamic Apex:

for(CustomObject__c co: lstCustomobjects) {
  String str = (String)co.get('customField1__c');
  // etc
}

Where sObject.get(String) is a method that accepts a field name, and returns an Object. This is then cast using (String) so that it can be assigned to a String variable.

However, note that this would throw an exception if the field does not exist, so a full solution would be to check for the field first:

if(sObjectType.CustomObject__c.fields.getMap().get('customField1__c') != null) {
  for(CustomObject__c co: lstCustomobjects) {
    String str = (String)co.get('customField1__c');
    // etc
  }
}

You must log in to answer this question.

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