So I have the below code which I created that dynamically creates and runs a query, and stores it within a type casted List. But I cannot figure out how to get it to work with the initial declaration 'public List'.
Is there a way to properly return the generated and casted list so that I can use it pass it into another function?
Thanks!
public List<SObject> queryObjectByName(Summary_Reporting__c sr)
{
//dynamic type casting of lists
String listType = 'List<' + sr.Object_to_Summarize__c + '>';
List<SObject> toCalc = (List<SObject>)Type.forName(listType).newInstance();
Try
{
String sel = '[SELECT Id, Name, ';
String selpt2 = 'FROM ' + sr.Object_to_Summarize__c + ' ';
String fieldToCalculate;
String selWhere = 'WHERE Date_Closed__c >= : sr.Period_Start__c and Date_Closed__c <= : sr.Period_End__c]';
if(sr.Type__c != null) sel += sr.Type__c;
if(sr.Object_to_Summarize__c == 'TASKRAY__Project_Task__c') fieldToCalculate = '(Time_to_Complete_minutes__c)aver';
if(sr.Object_to_Summarize__c == 'IT_Request__c') fieldToCalculate = '(Time_Spent_minutes__c)aver';
String generatedQuery = sel + fieldToCalculate + selpt2 + selWhere;
System.debug('Generated Query :: ' + generatedQuery);
List<SObject> returnList = (List<SObject>)Type.forName(listType).newInstance();
returnList = database.query(generatedQuery);
return returnList;
}
Catch(Exception E)
{
System.debug('Object Creation Exception :: ' + e);
}
}
Edit: MavensMate tosses this at me:
Non-void method might not return a value or might have statement after a return statement.
(Line: it's the System.debug inside the catch statement.)
Read through this to figure out the dynamic List casting: Apex Cast sObject list dynamically to a specific sObject Type