3

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

3

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.

  • This makes sense, thank you for explaining. I didn't realize I also needed to return even if null. Appreciate it! (I'm really glad it was something simple to learn/implement) – Genko Jul 29 '16 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.