Get the SObject Name from Record Id in Apex

To retrieve the name of the object from a record’s Id in Apex, you can use the Id.getSObjectType() method. This method helps identify the type of Salesforce object associated with a given record Id.


Steps to Get the Object Name from Id

1. Use getSObjectType()

The Id.getSObjectType() method returns the Schema.SObjectType for the given Id. You can then extract the object name from this.

Example Code:

public class ObjectNameResolver {
    public static String getObjectNameFromId(Id recordId) {
        // Get the SObjectType from the record Id
        Schema.SObjectType sObjectType = recordId.getSObjectType();

        // Retrieve the object name
        String objectName = sObjectType.getDescribe().getName();

        return objectName;
    }
}

How It Works:

  • recordId.getSObjectType(): Determines the SObject type from the Id.
  • sObjectType.getDescribe().getName(): Provides the name of the object, such as Account, Contact, or CustomObject__c.

2. Test the Function

You can test the method by passing an existing record Id:

Anonymous Apex Example:

Id recordId = '001XXXXXXXXXXXXXXX'; // Replace with an actual record Id String objectName = ObjectNameResolver.getObjectNameFromId(recordId); System.debug('Object Name: ' + objectName);