[SalesForce] To find Custom objects inside apex

I want to check whether a given object is standard or custom.
At present I have a method which identifies custom objects but that is taking too much CPU time, which leads to salesforce exception.

public static Boolean getAllCustomSObjects(String objectname)
{Boolean customobject;
List<String> sObjectList = new List<String>();
for(Schema.SObjectType objTyp : Schema.getGlobalDescribe().Values())
{
    Schema.DescribeSObjectResult describeSObjectResultObj = objTyp.getDescribe();
    if(describeSObjectResultObj.isCustom())
    { 
        String name = objTyp.getDescribe().getName();
        // Exclude all the unwanted Sobjects e.g. History, Share etc..
   /*     if(!name.containsignorecase('history') && !name.containsignorecase('tag')&&
         !name.containsignorecase('share') && !name.containsignorecase('feed'))
        {
            SobjectList.add(name);
        } */
        if(name.contains(objectname))
        {customobject=true;
        System.debug('Custom object found');
        }
        else
        {
         customobject=false;
         System.debug('Custom object not found');
        }
    }
}
system.debug('SObjectList****' + SObjectList);
return customobject;
}

Instead of fetching all the custom object names and checking whether the the given object name is a custom object, I want to check the object directly. I tried to modify the line

Schema.DescribeSObjectResult describeSObjectResultObj = objTyp.getDescribe(); 

and to give the object name as parameter for DescribeSObjectResult but it was throwing error.Do anyone help in this?

Best Answer

You don't need a for loop here. You can do something like

public static Boolean checkObjectType(String objectname) {
    SObjectType objToken = Schema.getGlobalDescribe().get(ObjectNameval);
    if(objToken  != null && objToken.getDescribe().isCustom())
        return true;
    return false;
}

This method will return true if it is custom object or false if it is not. Also one major difference is All custom objects end with __c with Standard object don't have these suffix.

Related Topic