Determine `SObject type` from relationship name without an exhaustive search

apexdescribefieldresultdescribesobjectsobject

Consider a general relation 'Foo.Bar' and some SObject type. An example might be 'Account.Id' and an Opportunity.SObjectType.

Can I determine SObjectType Foo is referring to without getting the field map and checking each DescribeFieldResult to find the field where getRelationshipName() == 'Foo' and then extracting potential types from getReferenceTo()?

Best Answer

If you know the field you want to examine at compile-time, then you can get the describe information for that field directly.

Opportunity.AccountId.getDescribe().getReferenceTo()[0].getDescribe().getName()

If this is more dynamic, and you don't know which field to examine until run-time, then there's no way around needing to get the field map from the DescribeSObjectResult, though since you can get a Map<String, DescribeFieldResult> (the keys are API names) you can simply get the specific field you're looking for.

Opportunity.SObjectType.getDescribe().fields.getMap().get('AccountId').getDescribe().getReferenceTo()[0].getDescribe().getName())

If you have an instance of an SObject with the target relationship field populated, you can use that Id to get at the SObject type

myOpp.AccountId.getSObjectType().getDescribe().getName()