Get the type (data type) of a field in apex

Using Describe Method:

Consideration Notes:

  • It consumes a lot of CPU time.
  • There is no governor limit on this.
String objectName = 'Account';
String fieldName = 'Name';

SObjectType r = ((SObject)(Type.forName('Schema.'+objectName).newInstance())).getSObjectType();
DescribeSObjectResult d = r.getDescribe();
System.debug(d.fields
        .getMap()
        .get(fieldName)
        .getDescribe()
        .getType());

Just a query – After Spring 20

Consideration Notes

  • Very less CPU time as it comes under SOQL which is not counted in CPU time calculation
  • Only 200 records can be queried.
public String getFieldDataType(String objectName, String fieldName){
            return [SELECT DataType FROM FieldDefinition WHERE EntityDefinitionId=:objectName AND QualifiedApiName=:fieldName LIMIT 1].DataType;
        }