Get Object Type By Record Id In Apex

by Rijwan Mohmmed
0 comment
get-object-type-by-record-id-in-apex

Hello folks, today we are going to discuss Get Object Type By Record Id In Apex. In Salesforce, record IDs begin with three character prefixes that define the standard and custom objects. A User record with ID 00561000000Mjya has the prefix 005, which is the prefix for User objects. 

See Standard Field Record ID Prefix Decoder for a list of prefixes.

Also, check this: Test Setup Method In Apex Salesforce

Key Highlights :

  1. We can get the Salesforce object name by record Id.
  2. We use recordId.getSObjectType().

Code :

FindSobjectNameCtrl.cls :

public class FindSobjectNameCtrl {
    public static String findObjectNameFromRecordId(Id recordId){
        String objectName = '';
        try{
            objectName = recordId.getSObjectType().getDescribe().getName();
            System.debug(objectName);
        }catch(Exception e){
            System.debug(e);
        }
        return objectName;
    }
}

call this method with recorded parameter by class name.

Id sId = '0016F00002Jk2YtQAJ';
System.debug(FindSobjectNameCtrl.findObjectNameFromRecordId(sId));
//output will be ==> Account

Reference :

  1. Find Object type from Record ID prefix
What’s your Reaction?
+1
1
+1
1
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.