How to Identify the Type of Object Based on Its ID
Sometimes, we may find ourselves performing a query on a record and returning a polymorphic lookup field value. Polymorphic fields can hold the ID of more than one type of object, such as User or Group. Now the question arises, how can we determine the type of the object that the ID we retrieved points to? One way to determine the object type is based on the way the ID is written. For example, the first three characters of the ID are unique to a specific object type. IDs for Groups, for instance, start with the sequence 00G. However, this method is not static or particularly readable.
Example
Lead myLead = [SELECT OwnerId, Owner.Name FROM Lead LIMIT 1];
if(String.valueOf(myLead.OwnerId).startsWith('00G')){
System.debug(LoggingLevel.Error, 'Hi! I am a Group!' + ' ' + myLead.Owner.Name);
}else{
System.debug(LoggingLevel.Error, 'Hello! I am NOT a Group!' + ' ' + myLead.Owner.Name);
}
A simpler way to perform the above check is by using the following concatenation of methods:
Lead myLead = [SELECT OwnerId, Owner.Name FROM Lead LIMIT 1];
String ownerType = myLead.OwnerId.getSObjectType().getDescribe().getName();
if(ownerType == 'Group'){
System.debug(LoggingLevel.Error, 'Hi! I am a Group!' + ' ' + myLead.Owner.Name);
}else{
System.debug(LoggingLevel.Error, 'Hello! I am NOT a Group!' + ' ' + myLead.Owner.Name);
}
In the second example, we used methods to extract the value we were looking for, making the comparison inside the if condition much more readable and clear.