I need to get the type (or data type) of a field (like if it is a date or integer for example) in apex.

I only have the name (api) of the object and the name of the field.

How can I do that ?

  • 1
    Type.forname with a describe call and fieldmap get will do it – Eric Jun 29 '18 at 10:28

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();
  • I can't compile your code sample, I got an error 'Method does not exist or incorrect signature: void SObject(Object)' at the first line – dou Jun 29 '18 at 12:07
  • Sorry about that, I lost a closing bracket somewhere along the line when I was formatting the code. I've updated my answers and it should work now. – Aidan Jun 29 '18 at 12:12
  • thanks, I will use your answer since it's more effective so ! – dou Jun 29 '18 at 12:21
  • Thx for expanding on my comment +1 – Eric Jun 30 '18 at 6:55

depends on what you want to get: SOAPType or DisplayType

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

Schema.DisplayType f = Schema.getGlobalDescribe() // or Schema.SOAPType
    .getType(); // or getSOAPType()

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.