0

I am trying to create a generic class to retrieve the type of a field for any sObject.

I am struggling with the following part of the code:

String[] fields = ['Id','Name'];   
for(sObject o : newRecordsFromTrigger){  
       for(String fieldName : fields ){
          // Need a generic method to get output as below
          // System.debug('field type +++'+Account.Id.getDescribe().getType());
          // above will work fine, but I want a generic method something as below.
          // System.debug('field type +++'+o.fieldName.getDescribe().getType());
       }
    }

1 Answer 1

3

there are two key points here:

  • get dynamically SObjectType from SObject by calling getSObjectType()
  • get map of fields by calling fields.getMap()

List<String> fields = new List<String>{'Name'};
SObject acct = new Account(Name = 'Test');

Map<String, SObjectField> fieldsMap = acct.getSObjectType().getDescribe().fields.getMap();
for(String field :fields){
    Schema.DisplayType displayType = fieldsMap.get(field).getDescribe().getType();
    System.debug('displayType: '+ displayType);
}

The result is:

displayType: STRING


you can also use singleton pattern or static class variables in order to optimize code and store across transaction previously checked sobjects and fields in a map.

1
  • Thanks. it worked Aug 27, 2021 at 12:04

You must log in to answer this question.

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