How to get SObjectType for a given Schema.SObjectField?

I have

Schema.SObjectField field = MyObject__c.myField__c;
Schema.SObjectType objectType = getTypeOf(field);

how would getTypeOfField() need to look like for this to be true?

System.assertEquals(MyObject__c.SObjectType, objectType);

Answer

I may be missing the boat here but why not a method based on the following?

// Build a map of hashcodes for each fieldDescribe taken from Schema Global Describe
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Map<Integer,Schema.SObjectType> fldHashCodeToSObjectTypeMap = new map<Integer,Schema.SObjectType>();

for (String sobjname: gd.keySet()) {
    for (Schema.SObjectField sobjField : gd.get(sObjName).getDescribe().fields.getMap().values())
        fldHashCodeToSObjectTypeMap.put(((Object) sObjField).hashCode(),gd.get(sobjName));

}

// Then compare your sobjectField in hand by hashing it and then looking up into the map
Schema.SObjectField field0 = Account.Industry; 
Integer field0Hash = ((Object) field0).hashCode();
Schema.SObjectField field1 = Opportunity.CloseDate; 
Integer field1Hash = ((Object) field1).hashCode();

System.debug(LoggingLevel.INFO,'field0 belongs to sobject:' + fldHashCodeToSObjectTypeMap.get(field0Hash)); 
System.debug(LoggingLevel.INFO,'field1 belongs to sobject:' + fldHashCodeToSObjectTypeMap.get(field1Hash));

Debug output yields:

17:58:06.113 (1113461278)|USER_DEBUG|[16]|INFO|field0 belongs to sobject:Account
17:58:06.113 (1113547114)|USER_DEBUG|[17]|INFO|field1 belongs to sobject:Opportunity

Your Util.getType(someSobjectField) method would simply do

fldHashCodeToSObjectTypeMap.get((Object) someSobjectField).hashCode());

on some static variable instantiation of fldHashCodeToSObjectTypeMap

Attribution
Source : Link , Question Author : Robert Sösemann , Answer Author : cropredy

Leave a Comment