function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shahamir SheikhShahamir Sheikh 

how to get object name of lookup field in apex

how to get object name of lookup field in apex
for ex:
I have obj customObj__c
In this obj have lookup field of Account name: customObj Account
Now I have obj Name : customObj__c and lookup field Name:customObj Account.
problem is that how to get releted  object Name(Account) by lookup fieldApiName(customObj_Account__r) and object. name(customObj__c )
AnkaiahAnkaiah (Salesforce Developers) 
Hi,

you can get it by using customObj_Account__r.Name

If this helps, Please mark it as best answer.

Thanks!!
Shams TabrezShams Tabrez
Hi Shahamir,

Use the below apex code. The account record Id will be shown instead of the account name if you query the list of customObj records but if you want the account name to show up in debug log then iterate the list and call the fields using a variable.
public class customObjInfo {
    
    public void getAccNames(){
        List<customObj__c> lstOfRecords = [Select Id, Name, customObj_Account__r.Name from customObj__c Limit 1];
        System.debug(+lstOfRecords);
        for(customObj__c cus : lstOfRecords){
            System.debug(' customObj Id: ' +cus.Id);
            System.debug(' customObj Name: ' +cus.Name);            
            System.debug(' customObj Account Name: ' +cus.customObj_Account__r.Name);
        }
    }
    
}
Call the method in the anonymous block:
customObjInfo custObj = new customObjInfo();
custObj.getAccNames();

If this is useful, please mark it as the best answer.

Thanks & Regards,
Shams Tabrez