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 : Trigger.new){

//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.


1 Answer 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());
  • Can we achieve the above using any of salesforce REST based APIs? May 25, 2015 at 12:12
  • 1
    Via the API I think the best thing you can do is check the key prefix from the global describe. Should be somewhat similar to the first code block in my answer - just using the api instead of apex methods to get the global describe. May 25, 2015 at 15:52
  • You might want to edit the getSObjectType method to be more prominent in your post.
    – Adrian Larson
    Jul 4, 2016 at 23:42
  • if (childRecord.ParentId != null && childRecord.ParentId.getSobjectType() == Case.getSObjectType()) { Oct 1, 2018 at 13:04
  • Hi @ca_peterson, I know this is a really old post but I was curious what are your thoughts on this PMD rule warning anIdProperty.getSobjectType().getDescribe().getName(); being fired when using this method.
    – Jose
    Sep 8, 2022 at 19:04

You must log in to answer this question.

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