Get SObject by Id

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 !

Answer

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.

Attribution
Source : Link , Question Author : SF_user , Answer Author : Phil Hawthorn

Leave a Comment