Determining Dynamically Whether A Salesforce Field Exists In APEX

Recently, I’ve been heavily involved in dynamic Apex and SOQL development. I encountered a requirement to create a custom AppExchange app capable of dynamically querying objects based on mappings provided by the admin and stored in custom settings.

Initially, I was querying to check if the field existed and returning true if there was a result, but this approach proved to be much slower compared to using describe methods.

I couldn’t find any clear guidance on how to accurately determine the existence of a field. Without delay, the doesFieldExist function will return true only if both the object and the field exist. However, if the object has been deleted and the code hasn’t detected that change, the function will return false. Similarly, if the object exists but the specified field does not, the function will also return false.

public boolean doesFieldExist(String objName, string fieldName)
    {
        try {
            SObject so = Schema.getGlobalDescribe().get(objName).newSObject();
            return so.getSobjectType().getDescribe().fields.getMap().containsKey(fieldName);
        }
        catch(Exception ex) {}
         
        return false;
    }