I have an Id and I want to know if it's possible to get the SObject with this unique ID ?

Something like :

SObject object = getSObjectById(myId);

I didn't find a method allowing that !


I'm not sure you could do exactly that, but what you could do is use the Id instance class to achieve what you need, for example:

Schema.SObjectType sobjectType = myId.getSObjectType();
String sobjectName = sobjectType.getDescribe().getName();

SObject record = Database.query('Select Id, Name From ' + sobjectName + ' Where Id = :myId');

See ID class documentation here for more details.

  • 1
    Yes, that's what I'm actually doing. But if there is no other way to do it, I will keep this code. Thank you for your help !
    – SF_user
    Jul 29 '14 at 9:31
  • 1
    I don't believe there is another way of doing it, certainly not one I have come across. You could also use the describe information to get all the field names too giving you a more 'complete' object. Jul 29 '14 at 9:33
  • 5
    This is great, just one thought. You can use string.valueOf() instead of getDescribe() there by improving performance. For example: String sobjectName = string.valueOf(myId.getSObjectType()); Aug 29 '18 at 12:18

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.