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

Determing SObject type in Polymorphic objects (i.e. ProcessInstance)

I received an email with the following inquiry:


Is there an easy way to determine the underlying SObject type when using objects that store polymorphic keys e.g. ProcessInstance? I tried the following :
for(ProcessInstance inst: [Select TargetObject.Id, Status, Id From ProcessInstance]){
                SObject sObj = inst.TargetObject;
And I get this:
8:6:22.566|CODE_UNIT_STARTED|[EXTERNAL]System Log Window
8:6:22.569|SOQL_EXECUTE_BEGIN|[1,27]|Aggregations:0|Select TargetObject.Id, Status, Id From ProcessInstance
Do I have to use the "Id" prefix to determine what Object the record is associated with?



And the answer to this is that yes using the ID prefix is one way to do this but an easier one is to recognize that polymorphic relationships like  ProcessInstance.TargetObject and Event/Task.who/what point to the Name object. The name object has a convenient "Type" field which provides the sobject type information. So simply adding that field to the above query should provide the information required in this inquiry:




for(ProcessInstance inst: [Select TargetObject.Id, TargetObject.type, Status, Id From ProcessInstance]){
SObject sObj = inst.TargetObject;

System.debug('The Type for id: ' + + ' is: ' + sObj.type);


Message Edited by mtbclimber on 03-08-2010 08:29 AM
Best Answer chosen by Admin (Salesforce Developers) 

Schema.DescribeFieldResult has a boolean method:isNamePointing() which allows you to programmatically determine if a field is a polymorphic relationship.  If you have a dynamic query and need to determine the sobject type at runtime, then I would recommend leveraging the above method to determine your code path for resolving the sobject type.


doc link