Use Case
Developer has a requirement to typecast specific object type from the name of SObject and try to update record of the SObject.
For example, SObject name is "Account" and Id is ''0012v00002AyZWE''.
Solution
Create an instance of SObject based on reflection as follows:
- String sObjectName = 'Account';
- SObject actObj = (SObject)(Type.forName('Schema.'+ sObjectName).newInstance());
We can also create an instance of SObject based on global describe as follows:
- String sObjectName = 'Account';
- SObject sObj = Schema.getGlobalDescribe().get(sObjectName).newSObject();
But, first one is most efficient which executes in 1ms where as second one takes 75ms and may be higher based on number of objects available at our Salesforce org.
So, lets put the desired solution:
- String sObjectName = 'Account';
- String recordId = '0012v00002AyZWE';
- SObject actObj = (SObject)(Type.forName('Schema.'+ sObjectName).newInstance());
- actObj.Id = recordId;
- actObj.put('Name', 'New Account2');
- update actObj;
We can easily put that in the list of SObject and update the records in one single goal.
If we have Id of a record then we can create an instance of SObject as follows:
If we have Id of a record then we can create an instance of SObject as follows:
- Id sampleid = '0012v00002AyZWE';
- SObject actObj = sampleid.getSObjectType().newSObject();
So, the entire solution approach will be as follows:
- Id sampleid = '0012v00002AyZWE';
- SObject actObj = sampleid.getSObjectType().newSObject();
- actObj.Id = recordId;
- actObj.put('Name', 'New Account3');
- update actObj;
Conclusion
From the above approaches which one needs to be followed that truly depends on individual use cases. It's good that Apex provides different ways to typecast SObject to specific object.
The article was up to the point and described the information very effectively. Thanks to blog author for wonderful and informative post.
ReplyDeleteSecurity Service