0

I have a doubt regarding the Schema.getGlobalDescribe() method which returns a Map.. I know that Schema.SobjectType is the Api names of Sobjects.. But I am not able to understand what does the keys of this Map represents!?Also Can anyone explain the difference between Sobject class and Schema.SobjectType class in Apex?

3

The key is the name of the type as a string. This lets you write logic using a string for the type, and then find out later if the type exists by seeing if there is a map value for that map key. This would typically be done in code that is configurable or that at run time discovers the types.

The SobjectType is a token from which an Sobject class can be created:

SobjectType t = Contact.SobjectType;
Sobject s = t.newInstance();

or from which descriptive information about the type can be obtained:

DescribeSObjectResult d = t.getDescribe();

Think of SobjectType as the starting point object for code that wants to work for multiple types. In code where the types are fixed, you will rarely need to use it.

See the SobjectType documentation.

By the way, you can get the SobjectType from an Id or from an Sobject - both have a getSObjectType() method. So, for example, if you had a collection of Id values you could work out the set of types involved:

Set<SobjectType> types = new Set<SobjectType>();
for (Id id : ids) {
    types.add(id.getSObjectType());
}
... types.size() ...

An example of using the map:

SObjectType t = Schema.getGlobalDescribe().get('FeedItem');
if (t != null) {
    // Code that requires chatter to be turned on
}
  • Thank you for the answer.. Can you please provide an example which requires the type discovery at run time? I want to know the scenario in which I will need to check whether the SobjectType exists for a given String name!? Thanks – Akshit Gupta Dec 16 '18 at 12:53
  • @AkshitGupta I've added an example scenario. More often needed inside a managed package that has to be designed to work in a variety of org configurations. Once-off code can be hardcoded to assume the org configuration. – Keith C Dec 16 '18 at 13:44

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.