In Salesforce some time we have requirement to retrieve object name from record ID. So We can done this by two approach.
- Get SObject type from record ID by using getSObjectType() method.
 - Convert Sobject type into string value.
 
1
2
3
4
 | Contact contactRecord = new Contact(FirstName = 'Test', LastName = 'Contact');
insert contactRecord;
// contactRecord.Id.getSObjectType() return Sobject Type of record then we convert them into String
String objectName = String.valueOf(contactRecord.Id.getSObjectType());
 | 
Second approach
- Get Sobject type from record id by using getSObjectType() method.
 - Describe Sobject type by using getDescribe() method.
 - Then get name of object from object describe by using getName() method .
 
1
2
3
4
5
6
7
8
 | Contact contactRecord = new Contact(FirstName = 'Test', LastName = 'Contact');
insert contactRecord;
/*
   - first we get Sobject type by using statement contactRecord.Id.getSObjectType()
   - we describe Sobject type by using getDescribe() method.
   - then from object describe by using getName() we can get name of that object 
*/
String objectName = contactRecord.Id.getSObjectType().getDescribe().getName();
 | 
