[SalesForce] Get Object API name of any Lookup field

I have requirement where I need the object name of any lookup field on any object.
for fetching lookup field I am using Schema class

Schema.DescribeFieldResult f = Schema.sObjectType.CustomOpportunity__c.fields.CustomTask__c;

for(Schema.SObjectType reference : f.getReferenceTo()) {
    System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
    System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
} 

This gives me the name and API name of the lookup object but I want to make it for any object so I changed above code to below

String objectName = 'CustomOpportunity__c';
String fieldName =  'CustomTask__c';
Schema.DescribeFieldResult f = 
Schema.sObjectType.objectName.fields.fieldName;

for(Schema.SObjectType reference : f.getReferenceTo()) {
    System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
    System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
} 

I know that It will throw an error saying Schema.SObjectType.objectName.fields does not exist or something.

I want to make this function generic function where I can pass the objectName and lookup fieldName and it returns me the Lookup object API name and Label Name.

Best Answer

Use Schema.getGlobalDescribe() method that accepts String as API name of object and then use getMap() method to get map of SObjectFields

String objectName = 'Opportunity';
String fieldName =  'AccountId';
Schema.DescribeFieldResult f = Schema.getGlobalDescribe()
    .get(objectName)
    .getDescribe()
    .fields
    .getMap()
    .get(fieldName)
    .getDescribe();

for(Schema.SObjectType reference : f.getReferenceTo()) {
    System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
    System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
}