Skip to main content

How to get an hierarchy of all objects dynamically through schema code in Salesforce

How to get a hierarchy of all objects dynamically through schema code in Salesforce I have code like below.

Set<String> strForRelatedObjects = new Set<String>();
Schema.SObjectType objectType = schema.getGlobalDescribe().get('child__c');

for(Schema.SobjectField strFld: objectType.getDescribe().fields.getMap().Values()){
    if(strFld.getDescribe().getType() == Schema.DisplayType.REFERENCE){
        strForRelatedObjects.add(string.valueof(strFld.getDescribe().getReferenceTo()).substringBetween('(',')'));         
    }
}

I want to fetch all parent object to object(Overall hierarchy). And above code should be in a position to get all the related objects to objects I want to fetch