Object Type from Object ID using globalDescribe()?


I am trying to use the following code to make a map of sObject Type Names and Object Prefixes:

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

I am a little unsure of what comes back from the GlobalDescribe or if im setting up my map correctly.  I will need to do a get() using an object id prefix and want to get back the object type name.  Can anyone assist me in accomplishing this?

thanks in advance

Asked on April 1, 2019 in APEX.
Add Comment
1 Answer(s)
Best answer

This should do it for you. Give it a shot!

public static Schema.SObjectType getObjectType(id subject){

Schema.SObjectType result;
string target = subject;

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

string keyPrefix;
for(Schema.SObjectType describe: gd.values() ){

keyPrefix = describe.getDescribe().getKeyPrefix();
if(keyPrefix != null && target.startsWith(keyPrefix)){

result = describe;




return result;


Answered on April 1, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.