I've created a custom object(File__c) which can be related to any standard or custom object. Currently I'm doing it with 2 fields, one to store the destination object id(String), and one for destination object type(String). If destination object type wasn't a variable, this would ideally be a lookup relationship.

Is there a way to create lookup using just the destination object id & without knowing the destination object type? Any other better way to do this?

  • I assume the ID is stored as a String, since you cannot create a polymorphic Lookup in custom objects (quite annoying). If so, the records will not be portable from one org to another. Anyway, an ID has a prefix that can be used to obtain the object type from that ID. Take a look at Id documentation for details. I have assumed you mean the object type rather than "record type", which would be RecordTypeId on the referenced SObject record.
    – Phil W
    Apr 7, 2022 at 7:22
  • You should edit the question to include object model details.
    – Phil W
    Apr 7, 2022 at 7:23
  • @PhilW thanks. Updated the question a little. I can save ID as string, but there is no way to make it a lookup relationship right?
    – vishesh
    Apr 7, 2022 at 7:34
  • Correct. So why do you need the object type separately? What do you use it for?
    – Phil W
    Apr 7, 2022 at 7:45
  • In apex, I need to get the associated record details and object type is used for those queries. With the ID prefix, I can avoid that
    – vishesh
    Apr 7, 2022 at 7:47

1 Answer 1


Every object type results in a unique (on the org) three character prefix applied to the IDs for the records of that object type.

Since you are storing the ID as a string, if you need to select File__c records that "relate" to records of a given object you can use DescribeObjectResult.getKeyPrefix to translate an object type to an ID prefix, thus:

String objectType = ...;
SObject obj = (SObject) Type.forName(objectType).newInstance();
DescribeSObjectResult describe = obj.getSObjectType().getDescribe();
String idPrefixLike = '%' + describe.getKeyPrefix();

You can then use this in your query, like:

List<File__c> files = [SELECT Id, ... FROM File__c WHERE RecordId__c LIKE :idPrefixLike ...];

(I have assumed the field holding the ID as a string is called RecordId__c.)

On the other hand, if you are simply getting File__c instances and want the RecordId__c translated to an object type, simply:

List<File__c> files = ...;

for (File__c file : files) {
    SObjectType objectType = Id.valueOf(file.RecordId__c).getSObjectType();


From SObjectType you can get the DescribeObjectResult as you need.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .