How do I return a dynamically casted list?

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?


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


To resolve the "non-void method might not return a value..." error, you must make sure you're returning a value (even null) during every possible code path. You'll see if you catch an exception, there's no further "return" statements. Adding "return null" in your catch block will work.

Category: apex Time: 2016-07-29 Views: 6

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.152 (s). 12 q(s)