Created
July 1, 2021 13:58
-
-
Save itsmebasti/4025c80cbdf4e38617a2f7dd3ac25014 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public without sharing class FieldDescribe { | |
private static final Map<String, SObjectType> SOBJECT_TYPES = Schema.getGlobalDescribe(); | |
private final SObjectField field; | |
public FieldDescribe(SObjectField field) { | |
this.field = field; | |
} | |
public SObjectType sObjectType() { | |
try { | |
new Account().put(field, null); | |
return Account.SObjectType; | |
} | |
catch (SObjectException e) { | |
return SOBJECT_TYPES.get(e.getMessage().substringBefore('.')); | |
} | |
} | |
// Note: only for demonstration purposes | |
public SObjectType sObjectTypeStable() { | |
for(ChildRelationship relationship : parentType().getDescribe().getChildRelationships()) { | |
if(relationship.getField() == field) { | |
return relationship.getChildSObject(); | |
} | |
} | |
return null; | |
} | |
public SObjectType parentType() { | |
List<SObjectType> parentTypes = parentTypes(); | |
if(parentTypes.size() > 1) { | |
throw new CustomException(field + ' is referencing multiple types'); | |
} | |
return parentTypes[0]; | |
} | |
public List<SObjectType> parentTypes() { | |
List<SObjectType> result = field.getDescribe().getReferenceTo(); | |
if(result.isEmpty()) { | |
throw new CustomException(field + ' is not a reference'); | |
} | |
return result; | |
} | |
class CustomException extends Exception {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment