QUESTION
I am trying to create a few utility methods that can work with any sObject that gets passed to it and return dynamic data-types. Unfortunately I'm starting to wonder, is this even possible?
EXAMPLE
Here is an example method I want for getting a list of sObject.Id
from a Map<Id,List<sObject>>
parameter.
public class Utils {
public static List<object> getFieldListFromMap (Map<Id,List<sObject>> object_map, String field){
List<object> objects = new List<object>();
for(Id id : object_map.keyset()){ //traverse through map
for (SObject obj : object_map.get(id) ) { //traverse through List of sObects
if(obj.get(field) != null) //exclude null values
objects.add(obj.get(field));
}
}
return objects;
// ^^ can I pass a string of the data-type and dynamically cast it?
}
}
The hope from this is I can pass something like:
Map<Id,List<CampaignMember>> members; // a map collection of CampaignMembers by ContactID
List<Id> campaign_ids = Utils.getFieldListFromMap(members, 'CampaignId');
OR
Map<Id,List<Quote>> quotes; // a map collection of quotes my ContactId
List<Currency> opportunities = Utils.getFieldListFromMap(quotes, 'Custom_Total__c');
If I cannot describe the field data-type by the <string>
parameter I'm passing here, then perhaps I can pass another <String>
parameter declaring the expected data-type that should return in the List
.
Any thoughts on this? Is it even possible? If not, what can be done, perhaps just dynamic sObjects but not fields?
Thanks in advance for any help I can get with this
EDIT: WORKING EXAMPLE
public static List<sObject> getListFromMap (Map<Id,List<sObject>> object_map, String obj_type){
List<sObject> objects = new List<sObject>();
Schema.SObjectType object_schema = Schema.getGlobalDescribe().get(obj_type);
for(Id id : object_map.keyset()){
for (SObject obj : object_map.get(id) ) {
objects.add(object_schema.newSObject(obj.Id));
// This gets the object type based on the objects Id
}
}
return objects;
}
List<CampaignMember> members = Utils.getListFromMap(campaign_members, 'CampaignMember');
List<Quote> quote_list= Utils.getListFromMap(quotes, 'Quote');
This method currently gets my back a List
of the object type I want back rather then just a generic sObect
type. Now I just need to be able to do this with fields as well.
Map<Id,List<sObject>>
to a method, I'd expect anarray
ofList<field-primitiveType>
to be returned (one for each ID in the Map) which I don't think is what you want. I suspect you want to pass aList<sObject>
and have aList<field-primitiveType>
returned instead.