1

Is it possible to access all of an objects fields through the schema class using a string? I know we can do this with an id.

Schema.DescribeSObjectResult sor = id.getSobjectType().getDescribe();

Is there a method by which we can do the following:

Schema.DescribeSObjectResult sor = 'Account'.getSobjectType().getDescribe();

2 Answers 2

6

Yes, you just pull the SObjectType out of the global describe.

SObjectType accountType = Schema.getGlobalDescribe().get('Account');
DescribeSObject accountDescribe = accountType.getDescribe();

Note that calling getGlobalDescribe() is quite CPU intensive and should be avoided in any sort of loop. Typically, if I expect to be retrieving a high volume of describes, I still implement a DescribeCache to save on this limit. In addition to performance, it also facilitates mocking if you make the class/methods virtual. It typically looks something like below:

public with sharing class DescribeCache
{
    static Map<String, SObjectType> objects = Schema.getGlobalDescribe();
    public static SObjectType getSObjectType(String objectName)
    {
        return objects.get(objectName);
    }

    static Map<SObjectType, Map<String, SObjectField>> fields =
        new Map<SObjectType, Map<String, SObjectField>>();
    public static SObjectField getField(String objectName, String fieldName)
    {
        return getField(getSObjectType(objectName), fieldName);
    }
    public static SObjectField getField(SObjectType sObjectType, String fieldName)
    {
        if (sObjectType == null) return null;
        if (!fields.containsKey(sObjectType))
            fields.put(sObjectType, sObjectType.getDescribe().fields.getMap());
        return fields.get(sObjectType).get(fieldName);
    }
}
1
4

Not quite like your example, but yes, this is possible.

One approach involves the Type class, which provides the little bit of reflection that the Apex language currently has.

Type t = Type.forName('Account');
SObject sobj = (SObject)t.newInstance();

DescribeSObjectResult accountDescribe = sobj.getSObjectType().getDescribe();

You must log in to answer this question.

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