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

The other two are right that you can use Schema.getGlobalDescribe(), but it is notoriously slow. Make sure that you either cache the global describe into a static variable so that you only call Schema.getGlobalDescribe() once per transaction, or consider the method from this question: Why is Schema.describeSObjects(types) Slower Than Schema.getGlobalDescribe()?

Which would look like this for your case:

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());

depends on what you want to get: SOAPType or DisplayType

String objectName = 'Opportunity';
String fieldName =  'AccountId';

Schema.DisplayType f = Schema.getGlobalDescribe() // or Schema.SOAPType
    .get(objectName)
    .getDescribe()
    .fields
    .getMap()
    .get(fieldName)
    .getDescribe()
    .getType(); // or getSOAPType()
System.debug(f);

This is a bit irritating in SF (from my point of view). But you can do it like this:

String objType=’YourObject’;
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType leadSchema = schemaMap.get(objType);
Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();

for (String fieldName: fieldMap.keySet()) {
  Schema.DisplayType fielddataType = fieldMap.get(fieldName).getDescribe().getType();
}

Tags:

Apex