I have a class with the following methods:
public virtual Map<String, List<SObject>> mapBySpecifiedStringField(List<SObject> homogeneousSObjectList, SObjectField idField) { if (homogeneousSObjectList == null || homogeneousSObjectList.isEmpty()) { return null; } String sObjectTypeString = String.valueOf(homogeneousSObjectList[0]?.getSObjectType()); String sObjectListTypeString = 'List<' + sObjectTypeString + '>'; Type dynamicListType = Type.forName(sObjectListTypeString); Type dynamicMapType = Type.forName('Map<String, ' + sObjectListTypeString + '>'); Map<String, List<SObject>> valueListByIdMap = (Map<String, List<SObject>>) dynamicMapType.newInstance(); for (SObject current : homogeneousSObjectList) { String value = (String) current.get(idField); if (value != null) { List<SObject> sObjectList = valueListByIdMap.get(value); if (sObjectList == null) { sObjectList = (List<SObject>) dynamicListType.newInstance(); valueListByIdMap.put(value, sObjectList); } sObjectList.add(current); } } return valueListByIdMap; } public virtual Map<Id, List<SObject>> mapBySpecifiedIdField(List<SObject> homogeneousSObjectList, SObjectField idField) { if (homogeneousSObjectList == null || homogeneousSObjectList.isEmpty()) { return null; } String sObjectTypeString = String.valueOf(homogeneousSObjectList[0]?.getSObjectType()); String sObjectListTypeString = 'List<' + sObjectTypeString + '>'; Type dynamicListType = Type.forName(sObjectListTypeString); Type dynamicMapType = Type.forName('Map<Id, ' + sObjectListTypeString + '>'); Map<Id, List<SObject>> valueListByIdMap = (Map<Id, List<SObject>>) dynamicMapType.newInstance(); for (SObject current : homogeneousSObjectList) { Id currentId = (Id) current.get(idField); if (currentId != null) { List<SObject> sObjectList = valueListByIdMap.get(currentId); if (sObjectList == null) { sObjectList = (List<SObject>) dynamicListType.newInstance(); valueListByIdMap.put(currentId, sObjectList); } sObjectList.add(current); } } return valueListByIdMap; } As you can see, the logic is very much the same, only the key is a different type. And in the future, I might need additional similar methods if the SObjectField provided for mapping has some other type (such as a number or a date).
Is there some way I can determine from the provided SObjectField an appropriate type to use for the key? And if I were to do so, would I have alternatives to throwing away type safety (returning Map<Object, List<SObject>>)?
Object? Do you really benefit from type safety in this scenario?List<Object>toList<SpecificType>, but you can still usecontainsand the like...Object. Your choice :)