38

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){
   parentIds.add(a.ParentId);
}

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

57

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 = 
Schema.getGlobalDescribe(); 
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());
        break;
    }
}
| improve this answer | |
  • Can we achieve the above using any of salesforce REST based APIs? – user1986059 May 25 '15 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. – ca_peterson May 25 '15 at 15:52
  • You might want to edit the getSObjectType method to be more prominent in your post. – Adrian Larson Jul 4 '16 at 23:42
  • if (childRecord.ParentId != null && childRecord.ParentId.getSobjectType() == Case.getSObjectType()) { – Andrii Muzychuk Oct 1 '18 at 13:04

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.