Find your content:

Search form

You are here

Infering sObject Type from Id or collection of Id's


If I have an instance of an Id variable that has been populated with a value, is there way to infer the sObject type of that Id using a describe call.

So if I did:

Set<id> parentIds = new Set<id>();

for (Attachment a :{

//and here, I want to find out what are the parent records of these attachments. 

Presuming all ParentId values are identical sObject types, is there anything I can do to check this?

And a follow-on: Can I infer sObject type from Id instance at all? Seems that could be handy at times.

Attribution to: pchittum

Possible Suggestion/Solution #1

in APIv26 there's a new method, Id.getSObjectType() which returns a sObject token you can use to find it's type. Sample code:

String objectAPIName = someId.getSObjectType().getDescribe().getName();

This new style uses much less heap space and script statementsCPU time in addition to being much simpler and is highly recommended.

Don't do this anymore, but traditionally you could use the global describe to check the key prefix of each sObject type against your record Id and if they matched you knew what type of record it is. A sample of doing this (shamlessly stolen from Andrew Fawcett):

String myIdPrefix = String.valueOf(someId).substring(0,3); //get just the prefix
Map<String, Schema.SObjectType> gd = 
for(Schema.SObjectType stype : gd.values())
    Schema.DescribeSObjectResult r = stype.getDescribe();
    String prefix = r.getKeyPrefix();
    System.debug('Prefix is ' + prefix);
    if(prefix!=null && prefix.equals(myIdPrefix))
        System.debug('Stop hammer time! ' + r.getName());

Attribution to: ca_peterson
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content