I see how to get an sObject, given an id... (Get SObject by Id)

How could I do so given the sObject name??

string objectName = 'Account'; //(could be any object name)
//doesn't work ==> sObject myObj = objectName.getSObjectType();

Thank you


You can use getGlobalDescribe which returns map of Map<String,SObjectType> SObjectName and related SObjectType.

SObjectType currentType = Schema.getGlobalDescribe().get('Account');



Schema.getGlobalDescribe() will work, but it is an expensive operation and thus should be used sparingly. I believe best practice here involves having an Apex class to proxy requests for getGlobalDescribe() so that you only ever call it once per transaction (and then store the results in a static variable).

If you don't want to bother with that, then another option would be to use the Type class that Salesforce provides. That'll be able to get you an SObject, which has getSObjectType().

Type t = Type.forName('Account');
SObject sobj = (SObject)t.newInstance();
system.debug(sobj.getSObjectType() == Account.SObjectType);
  • Yeah this approach is actually the best practice.
    – Adrian Larson
    Jan 12 at 17:09
  • Thank you all. Awesome stuff!
    – Pete
    Jan 12 at 22: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.