Convert String to sObject in Salesforce Apex

While building a custom app in our Salesforce org, I added a feature where users can input the object’s name and other fields as strings. That dynamically creates and populates records based on user input or another source.

In this case, I had to create an account record using a string to specify the object type and then set some field values for this new record.

For this, I converted the input strings to the Salesforce Apex sObject data type, which converted the input strings to an account object record in the database.

In the steps below, I will explain how to convert a string to a sObject in Salesforce Apex using the Class method.

Convert String to sObject in Salesforce Apex

To convert a string to sObject in Salesforce Apex, navigate to the Salesforce developer console and follow the steps below.

  1. To create a new class in the developer console, select File > New > Class.
  1. Enter the Name for the new apex class and click the OK button.
  1. Enter the code below in the new Apex class and save it.
public class StringToSObject {
    public static void createDynamicRecord() {
        String str = 'Account';
        sObject obj = Schema.getGlobalDescribe().get(str).newSObject();
        
        obj.put('Name', 'Boston textiles');
        obj.put('Description', 'Primary account for the boston textiles');
        
        System.debug('sObject - ' + obj);
        insert obj;
    }
}
  • The sObject obj will create a new instance ( a record) based on the object type string. For example, if a string is ‘Account,’ a new account record will be created.
  • obj.put instances will populate the sObject fields with values. We can add multiple obj.put instances for multiple fields.
  • At last, insert obj will insert the record in the object database. (optional)
  1. If the above code has no problems (errors), execute the anonymous window with shortcut keys “Ctrl+E.”
  1. Enter the code below to execute the class method in the anonymous window. After that, click the Execute button.
ClassName.MethodName();
Convert string to Sobject in Salesforce apex
  1. In the Execution log window, select the checkbox to debug only, and there you will see the string converted to sObject with the fields of the sObject.