Fetch all Custom Objects in APEX

Fetch all Custom Objects in apex
Fetch all Custom Objects in apex

In this article we will give you simplest way to get all custom objects in apex using Schema.getGlobalDescribe().

You know that using Schema.getGlobalDescribe() we can fetch all properties of sObject. We have already used Schema class to fetch all Standard objects , record types from object ,  find all required fields on Object and so on .

Get List of all Custom Objects

We know that every custom object ends with  __c . Here we are going through  all objects present in Salesforce org and if Object contains __c then we are considering  that object as custom object and print that object local name using getLocalName method .

				
					for(Schema.sObjectType info : Schema.getGlobalDescribe().values()) { 
    Schema.DescribeSObjectResult describedInfo = info.getDescribe();
    String objectName = describedInfo.getLocalName();
    if(objectName.contains('__c')) { 
        System.debug('Object Name '+objectName );
    }
}
				
			

The about code will give you all custom objects . Check how to find all the Standard Objects in Salesforce. Also here you can find how to filter Standard objects in APEX.

Hope you learn something new Today .

Thank you…

How the code works

Schema.getGlobalDescribe() returns a Map of every object in the org. The loop describes each object, reads its name and prints it when the name contains __c, which is the suffix of custom objects.

Problems in this version

  • Calling getDescribe() on every object in the org is expensive. In a large org it uses a lot of CPU time.
  • contains('__c') matches anywhere in the name. endsWith is more accurate.
  • Other custom types use different suffixes: __mdt for custom metadata, __e for platform events, __b for big objects and __x for external objects. They are not matched here, which is usually what you want.

Faster version

List<String> customObjects = new List<String>();
for (String objName : Schema.getGlobalDescribe().keySet()) {
    if (objName.endsWith('__c')) {
        customObjects.add(objName);
    }
}
customObjects.sort();
System.debug(customObjects);

The Map keys are already the object names in lowercase, so no describe call is needed.

FAQ

Do the names include the namespace?
Yes. Objects from a managed package look like ns__Student__c.

Can I get the labels as well?
Yes. Call getDescribe().getLabel() on the objects you really need, not on all of them.

Leave a Reply