how to get object name from id / prefix value in salesforce

Standard and Custom Objects in Salesforce have three character prefixes which form the first part of the record ID. 

For example, a User record with ID 00561000000Mjya has the prefix 005, which is the prefix for the User object. 

To get an Id from RecordId / Record Prefix, you can use below class.
----------------------------------------------------------------------------------------------------
public class SchemaGlobalDescribe{
    public static String findObjectNameFromRecordIdPrefix(String recordIdOrPrefix){
        String objectName = '';
        try{
            //Get prefix from record ID
            //This assumes that you have passed at least 3 characters
            String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3);
             
            //Get schema information
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
             
            //Loop through all the sObject types returned by Schema
            for(Schema.SObjectType stype : gd.values()){
                Schema.DescribeSObjectResult r = stype.getDescribe();
                String prefix = r.getKeyPrefix();
                System.debug('Prefix is ' + prefix);
                 
                //Check if the prefix matches with requested prefix
                if(prefix!=null && prefix.equals(myIdPrefix)){
                    objectName = r.getName();
                    System.debug('Object Name! ' + objectName);
                    break;
                }
            }
        }catch(Exception e){
            System.debug(e);
        }
        return objectName;
    }

}

--------------------------------
Now you can execute below code in developer console.
String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('500');

System.debug(objectName);

I hope this will help you.


Reference URL:
https://help.salesforce.com/articleView?id=How-to-find-Object-Type-from-Record-ID-Prefix&language=en_US&type=1



Comments

Popular posts from this blog

System.AsyncException: The Apex job named is already scheduled for execution.

Custom Setting Creation in Apex Test Class

Error : "Trigger must be associated with a job detail"

AJAX Toolkit Debug Shell

Salesforce Trace Log Query Using Apex

How to Query All the batch classes in your Salesforce Instance using APEX

Creating Salesforce Developer Account

Creating MAP from SOQL Query

Custom Pagination Without Controller (Apex)