Instantiating an empty list of SObjects

You’re building a dynamic Apex class so general you’re thinking about promoting it to colonel. You’ve slogged through the Salesforce documentation on the topic, a feat in itself, but are having issues instantiating an empty list of SObjects to be processed in some way. If you attempt to do this in the seemingly Salesforce manner i.e. [code language=”java”] List<SObject> sobjects = new List<SObject>(); [/code] You will receive the following error: Compile error: Only concrete SObject lists can be created This can be rather frustrating as this type of data structure is one of the more commonly used. There are however 3 workarounds, one slightly more elegant than the rest. NB myObject is a SObject. [code language=”java”] List<SObject> sobjects = Database.query(‘select id from ‘ + myObject.getSObjectType() +’ where id=null’); [/code] [code language=”java”] String searchquery=’FIND\’xxx\’IN ALL FIELDS RETURNING ‘+ myObject.getSObjectType() +'(name)’; List<List<SObject> searchList=search.query(searchquery); List<SObject> sobjects = searchlist[0]; [/code] or finally you could …

Read more