Handy Apex Code : DIY sObjectType.newSObjects()
Posted by Tom Patros
on Monday, February 01, 2010
While working on some dynamic Apex code recently, I discovered the very-handy sObjectType.newSObject() method, which basically creates a new (if no parameter is provided) or existing (if a Salesforce ID parameter is passed) generic sObject. This has been great for writing generic record creation and manipulation code that can respond dynamically to any sObjectType.
I was expecting to see a sObjectType.newSObjects() method that would be the List-based "plural" version of the same. Alas, this does not exist, but you can use Database.query() (which returns a List of sObjects) to simulate this. Basically, you write SOQL that attempts to select objects of a given type with a blank SFID (which never happens) and you'll get an empty List of sObjects back.
Here's some code:
String objectName = 'Contact';
// get a sObjectType object
Schema.sObjectType sObjectType =
Schema.getGlobalDescribe().get(objectName);
sObject sObj;
List<sObject> sObjects;
// create a new generic sObject
sObj = sObjectType.newSObject();
// or get an existing generic sObject
sObj = sObjectType.newSObject(some_sfid);
// shucks, this doesn't exist
sObjects = sObjectType.newSObjects();
// but we can fake it
sObjects = Database.query(
'select Id from ' + objectName + ' where Id = \'\'');
After that last line, you'll have an empty generic sObject List that you can then fill with your generic sObjects. How generic!
Care to Comment?