[SalesForce] Apex cast List into List

My method returns a list of Object. I wanted to add that to a list of specific SObject.

List<Account> accList = new List<Account>();
List<Object> objList = new List<Object>(returnRecordList(List<Account>.class, recordList));

accList.addAll((List<Account>)objList);

static List<Object> returnRecordList (Type resListType, List<SObject> records) { 

    List<Object> prefEnabled = (List<Object>)resListType.newInstance();
    system.debug(prefEnabled);
    return prefEnabled;
}

I get the error as Invalid conversion from runtime type List<ANY> to List<Account>

Best Answer

You can't add store an Object in an Account, nor a List of Object in a List of Account.

If, and only if, you're sure it's the correct type, you can "cast" to override:

accList.addAll((List<Account>)objList);

If the type is invalid at runtime, you'll get a TypeException.

You note that sometimes your method will return a Boolean, so this would be unacceptable for a List of Account. You'd have to check first:

if(objList instanceOf List<Account>) {
  accList.addAll((List<Account>)objList);
}
Related Topic