+ 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