How to retrieve SObject using Schema.SObjectType class?

365    Asked by Aalapprabhakaran in Salesforce , Asked on May 4, 2023

I am trying to create a dynamic class to retrieve a record for update. I struggle with the following part of the code:

targetSObject = new sor.getSObjectType()(ID = sObjectID);
For example, if this were an account record, I would want the result to be:
targetSobject = new Account(ID = '0016A000003tqQfQAI')
Essentially what I am asking is how do I recreate the above example using the Schema class.
Also, I am curious what the community thinks about retrieving records using the new Sobject(ID = '...')
public with sharing class UpdateAccountGoalsFromOpp {
    Map> sorToUpdate = new Map>();
    public SObject getSObject(ID sObjectID)
        Schema.DescribeSObjectResult sor = sObjectID.getSobjectType().getDescribe();
        String recObject = String.valueOf(sor.getName());
            sorToUpdate.put(recObject, new Map());
        SObject targetSObject = sorToUpdate.get(recObject).get(sObjectID);
        if(targetSObject == null)
            targetSObject = new sor.getSObjectType()(ID = sObjectID);
            sorToUpdate.get(recObject).put(sObjectID, targetSObject);
        return targetSObject;
After doing research:
targetSObject = Schema.getGlobalDescribe().get(recObject).newSObject(sObjectID);
^ I think the above code may be the equivalent to:
targetSobject = new Account(ID = '0016A000003tqQfQAI')
Answered by Buffy Heaton

To retrieve SObject using Schema.SObjectType class-

From the sObjectType object, use the newSobject method to create a new record in memory. It accepts a single optional parameter for the record Id:
targetSObject = new sor.getSObjectType().newSobject(sObjectID);
As an aside, if you already know the Id, you don't need the describe:
targetSObject = sObjectID.getSobjectType().newSobject(sObjectID);
Also, you can use an sObjectType token instead of a string to avoid a describe call entirely:
Map> sorToUpdate = new Map>();
sObjectType sot = sObjectID.getSobjectType();
if(!sorToUpdate.containsKey(sot)) {
  sorToUpdate.put(sot, new Map());

Your Answer


Parent Categories