Is there a way to instantiate an SObject?

I have done the following:

Id objId = 'a0Ci000000vd7xA';            
String objName = ((Id)objId).getSobjectType().getDescribe().getName();

Type t = Type.forName(objName); //object name
Sobject  myObj =  (Sobject)t.newInstance();

myObj.emp_name__c = 'test';

Field expression not allowed for generic SObject


You don't need to go through the complicated method you went through to get the new record. The following works just as well:

Id objId = 'a0Ci000000vd7xA';
SObject record = objId.getSObjectType().newSObject(objId);

This approach also has the advantage that it also works even if someone does something silly like creating a class called "Account" and you try to instantiate an Account record.

If you want to use the static methods, you have to first cast to a concrete type:

CustomObject__c record = (CustomObject__c)objId.getSObjectType().newSObject(objId);

However, if you want to use the object generically, you use the get/put SObject methods:

record.put('Name','New Name Value');
  • I will be dealing with sObject meaning that I cann't have hard code any object name, if i have something like this then getting the same error that i have posted above, so here is what i'm trying to do instead of hard-coding i'm getting the value by running soql in results var and assigning to it record.put('Name', results.name); – Nick Kahn Mar 23 '17 at 20:32
  • @NickKahn You can use the get method to get a field's value dynamically as well. – sfdcfox Mar 23 '17 at 20:33

If you want to put values into fields, you can use the generic put methods:

SObject record = Id.valueOf('a0Ci000000vd7xA').getSObjectType.newSObject();
record.put('emp_name__c', 'test');

Or you can also use a SObjectField:

record.put(SomeObject__c.SomeField__c, 'Some Value');
  • Would be worth getting the Id and then passing it to the newSObject() call. – zgc7009 Mar 23 '17 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.