function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
uat_live1.3903047664538198E12uat_live1.3903047664538198E12 

Create an SObject Instance of Custom Type

Hi All,

I need to create an Instance of an Object at runtime. I change the ObjectType string at runtime in the below code.

String ObjectType = 'Cars__c';
Type t = Type.forName(ObjectType);
 sObject newObj = t.newInstance();
newObj.Name = 'test';
insert newObj;

I get an error like  "Compile Error: Illegal assignment from Object to SObject "

Anywere in the code I should not have the hardcoded APIs like Cars__c. I get all these from custom settings.Could someone please guide me.
Kindly also let us know the difference between SObject and Object.
Thanks and Regards,
Chirstwin
Shaijan ThomasShaijan Thomas
String sObjectName = 'Account';
Schema.SObjectType t  = Schema.getGlobalDescribe().get(sObjectName);
SObject s = t.newSObject();
s.put('Name','test');
insert s;

Check whether this will help you
Thanks
Shaijan
Frédéric TrébuchetFrédéric Trébuchet
Hi,

Here a simple example to dynamically create an object:
String sObjectName = 'Car__c';
Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName); // obtain sObject description from the schema
SObject s = t.newSObject(); // create a new instance of that sObject
s.put('Name', 'Mustang'); // set name
insert s; // insert to the related database object
Then, considere sObject as the generic representation of a record of any object (standard or custom) that can be stored in the Force.com platform database like Opportunities, Leads or Cars__c. sObjects are used by APEX developers.
On the other hand, object refere to the specific representation of one object type. So, when you define a variable of type "Lead", it matches with the Lead definition.
Maybe not very clear so, in short, sObject variable = one record of any type and Object variable = one record of the designed object type.

Hope this helps,
Fred
 
Sushant PatilSushant Patil
String ObjectType = 'Cars__c';
Type t = Type.forName(ObjectType); //Creating a type class instance
sObject newObj = (SObject)t.newInstance(); //Converting a type class instance to a SObject instance using typecasting
newObj.put('Name','test'); //Putting value in the name field of SObject instance
insert newObj; //insert the record
Just a more simplfied answer to what is given above. Instead of using the Schema.getGlobalDescribe() we can simply typecaste the type class instance to a SObject type.
The forName() method has a return type System.Type which simply means it is of class Type. This cannot be directly converted to a SOject type which is the reason for the error you are getting. So explicitly convert it to SObject instance using typcasting.Hope this helps you.

Thanks
Sushant