function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nagaraju Mogili 25Nagaraju Mogili 25 

how can we know the object name and related records from apex code by using first 3 digits of object id or record id ..?

Best Answer chosen by Nagaraju Mogili 25
Raj VakatiRaj Vakati

You can use  getKeyPrefix() method the   sObject Describe Result object:


Returns the three-character prefix code for the object. Record IDs are prefixed with three-character codes that specify the type of the object (for example, accounts have a prefix of 001 and opportunities have a prefix of 006).
 
//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;
                }
            }




https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject_describe.htm?search_text=getKeyPrefix



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

https://salesforce.stackexchange.com/questions/70517/how-to-get-id-prefix-if-you-know-the-object-name