I've created a method to extract a specific field from a list of sObjects, and since it accepts any sObject, I return a list of Object
too, since field types can vary.
So the method is as follows:
public static List<Object> getFieldFromSobjectList(List<SObject> objects, String field_name) {
List<Object> result = new List<Object>();
for (SObject obj : objects) {
try {
result.add(obj.get(field_name));
} catch (Exception e) {
// ... shh bb is ok
}
}
return result;
}
The method returns a list of objects and I'm trying to convert the result to a list of ids, using casting:
List<Id> list_of_ids = (List<Id>) Utils.getFieldFromSobjectList(list_of_objects, 'Id');
Even though this code can be compiled, at runtime it throws me an error:
System.TypeException: Invalid conversion from runtime type List<ANY> to List<Id>
List<ANY>
instead of aList<Object>
), but as a workaround, have you tried iterating over the resulting list and casting individual objects asId
instead of trying to cast the entire list?