2

Does anyone know if there is an approach to write a generic method that takes an SObject list and specified type as input, and return a downcasted list? Casting is straightforward but as far as I'm aware there is no way to dynamically specify the return type of a method and I'm trying to avoid writing a bunch of overloaded methods for every possible return type I would want

For example:

public static **CastedList** castList(List<SObject> sobjectList, String castType) {
    //create the list

    //do some casting

    return castedList
}
3
  • 1
    Down-casting is a lot more trouble than up-casting. Apex doesn't really have the features needed to do this dynamically. This is probably an indication that you should rethink the implementation or architecture of the code that depends on this working.
    – Derek F
    Dec 5, 2016 at 19:47
  • 2
    No cast is required. Salesforce will happily let you assign a generic sobject list to a typed list. You definitely don't need to cast in the method.
    – sfdcfox
    Dec 5, 2016 at 19:48
  • Thanks for the replies. Derek has a good point, I'll just cast directly for now as needed. Dec 6, 2016 at 0:35

1 Answer 1

0

You do not need to downcast in method. Instead, downcast in statement from where you are calling the method:-

Generic method takes Sobject list and return Sobject list

public static List<SObject> castList(List<SObject> sobjectList, String castType) {
    //create the list

    //do some casting

    return castedList
}

Some code:

List<Account> accounts = (List<Account>)castList(sObjectList, 'Account');

//or

List<CustomObject__c> customObject = (List<CustomObject__c>)castList(customObjectList, 'CustomObject__c');
5
  • 2
    If OP already has an sObject list, and there's no casting happening in the method, then what's the point in calling the method?
    – Derek F
    Dec 5, 2016 at 19:41
  • 1
    You don't even need to cast, unless you're trying to iterate the List<SObject> directly in a for loop.
    – Adrian Larson
    Dec 5, 2016 at 19:42
  • @AdrianLarson I believe OP would iterate element as he has "castType" param in method. There is no casting needed if we need to DML. We can again assign it to some SObject list.
    – Ashwani
    Dec 5, 2016 at 19:44
  • Actually if you need to upsert that's the one time you do need to downcast. It can be done.
    – Adrian Larson
    Dec 5, 2016 at 20:26
  • Downcast is safest way :) . Id should work in Sobject upsert!
    – Ashwani
    Dec 5, 2016 at 20:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .