16

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 !

1 Answer 1

24

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.

3
  • 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, 2014 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, 2014 at 9:33
  • 6
    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, 2018 at 12:18

You must log in to answer this question.

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