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<String, Map<Id, SObject>> sorToUpdate = new Map<String, Map<Id, SObject>>();

    public SObject getSObject(ID sObjectID)
        Schema.DescribeSObjectResult sor = sObjectID.getSobjectType().getDescribe();
        String recObject = String.valueOf(sor.getName());

            sorToUpdate.put(recObject, new Map<Id, SObject>());

        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')
| improve this question | | | | |

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<sObjectType, Map<Id, sObject>> sorToUpdate = new Map<sObjectType, Map<Id, sObject>>();


sObjectType sot = sObjectID.getSobjectType();
if(!sorToUpdate.containsKey(sot)) {
  sorToUpdate.put(sot, new Map<Id, sObject>());
| improve this answer | | | | |
  • Amazing, Thank you so much! I just started learning the Schema class today and still really do not understand how to navigate the class. I am beginning to notice patterns, but I am still quite lost on this. – Matthew Metros Apr 27 '19 at 4:10

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.