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();
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.Sign up to join this community
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
Type t = Type.forName('Account'); SObject sobj = (SObject)t.newInstance(); system.debug(sobj.getSObjectType() == Account.SObjectType);