Does anybody have a good way of mapping a key prefix to an object type?

I want to be able to reliably take an ID and map it to the appropriate object type so I can query the object in question.

Before now I’ve tried using the global decsribe info, looping over the objects and comparing the value of getKeyPrefix() witht the test value, but the problem is we’re limited to 100 describe calls in the governor limits, and so this method breaks down in orgs with more than 100 objects.

The next best solution I can think of is to slowly build up map of prefix -> object inside a list custom setting, so if I miss an object first time around the second time I might get it and so on as each successive run will have a larger cache to test first. This doesn’t seem ideal though, so I’m looking for other options.

Another might be to hard code the known prefixes 006 for Oppties etc. in a static apex map, but that feels dirty.

Answer

Despite what the docs would seem to indicate you are allowed to call getDescribe() on over 100 SObjectType objects in order to get their key prefix (the limits seem to apply to enumerating fields and global describes).

I have an answer on a similar question with details on how to implement your idea, but there is a much cleaner way of doing this. To quote from the answer:

In APIv26 there’s a new method, Id.getSObjectType() which returns a sObject token you can use to find it’s type. Sample code:

String objectAPIName = someId.getSObjectType().getDescribe().getName();

This does not appear to be limited to 100 calls either, so you should be able to use this on very large numbers of IDs.

Attribution
Source : Link , Question Author : Matt Lacey , Answer Author : Community

Leave a Comment