Best way to get the object name from record id in apex

Published by

on


Sometimes you have to identify the object name associated with the record id in your apex code. In that case use of prefix may hit the code quality check report (like PMD report). And for that case you can use sObject method getsobjecttype() to get the object name. See below example.

Run the below code in ‘Execute Anonymous Apex’ in developer console.

Id recordId = '0016F00003E2WS0QAN'; 
System.debug('object name>> '+ recordId.getsobjecttype());

/**
Output:
00:08:15:003 USER_DEBUG [2]|DEBUG|object name>> Account
**/

//Use Case: If record id is Account then do something
Schema.SObjectType AccountObject = Schema.Account.getSObjectType();
Schema.SObjectType record = recordId.getsobjecttype();
If(record == AccountObject){
   //Do Something
}