I have a SOQL query where I don't know the FROM
object, meaning it can change every time. So I dynamically populate it like so
// dynamicObject is a String.
String queryString = 'SELECT '
+ ' Id, Name ' +
+ ' FROM ' + dynamicObject;
List<sObject> sourceObjects;
// Downcasting from a generic list of sobjects to the particular type of the object.
sourceObjects = (List<SObject>)Type.forName('List<' + dynamicObject + '>').newInstance();
sourceObjects = Database.query(queryString);
As you can see I am downcasting from a generic sObject type to a specific one. I used this solution: Dynamically assign the dataType of a Set
However now I am trying to iterate over this list of results and the only way I can iterate is if I use the SObject
type which does not recognize the Name
field I queried for.
I tried doing something like this:
SObject dynamicType = (SObject)Type.forName(dynamicObject).newInstance();
for(dynamicType obj: sourceObjects) {
//something
}
However that comes back as Invalid type: dynamicType
.
Is there a way to iterate over the List where I will be able to reference the Name field that's part of the query?