3

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>

0

1 Answer 1

4

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);
}
3
  • Thanks sfdcfox. I did try this. Error received - Invalid conversion from runtime type List<ANY> to List<Account>. And yes I will know the exact SObject or whether it will return a Boolean, so that's not an issue. Commented Apr 6, 2021 at 20:20
  • @sfdeveloper21 The method you're calling will need to create an actual List<Account> for it to work, or you'll have to loop over the elements one at a time: for(Object obj: objList) { if(obj instanceof Account) { accList.add((Account)obj); } }
    – sfdcfox
    Commented Apr 6, 2021 at 20:22
  • Thanks. This seems to work fine, but now I am suspecting that whether my method is actually returning a list of Account. The returnRecordList is something like this - static List<Object> returnRecordList (Type resListType, List<SObject> records) { List<Object> prefEnabled = (List<Object>)resListType.newInstance(); system.debug(prefEnabled); return prefEnabled; } Commented Apr 6, 2021 at 20:27

You must log in to answer this question.

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