Skip to content

Instantly share code, notes, and snippets.

@itsmebasti
Created July 1, 2021 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsmebasti/4025c80cbdf4e38617a2f7dd3ac25014 to your computer and use it in GitHub Desktop.
Save itsmebasti/4025c80cbdf4e38617a2f7dd3ac25014 to your computer and use it in GitHub Desktop.
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