How to convert String to sObject using Apex in Salesforce?

How to convert String to sObject using Apex in Salesforce?

Schema.getGlobalDescribe().get().newSObject() can be used to convert String to sObject using Apex in Salesforce.

Sample code:

//Setting String str as Account
String str = 'Account';
//Casting String to sObject
sObject obj = Schema.getGlobalDescribe().get(str).newSObject();
obj.put('Name', 'Test');
obj.put('Description', 'Testing');
system.debug('obj is ' + obj);

Output:

Leave a Reply