You need to sign in to do that
Don't have an account?

How to get sObject type from the Id?
How to get sObject type from the Id?
I dont want to use the SOSL query approach or the exception handling approach. Is there any other straight forward way I can get the API name of the object if i pass the Id?
I attempted something like below
If(Account.sObjectType==new sObject (sId).getsObjectType())
expecting new sObject (sId).getsObjectType() to return Account.sObjectType if 'sId' belongs to an accoun record.
Please help and share your experience when you encountered similar situation.
~Sachi
If you use Schema.getGlobalDescribe(), you may iterate through the returned objects to find the object which has the keyPrefix that matches the leftmost three characters of the ID. If you need this repeatedly, you can use a map<string,string> to map the keyPrefix to the API name, like this:
Once you have keys populated, you can then determine a record's type using keys.get(String.valueOf(recordId).substring(0,3)). This is technically the long way around, but there isn't any way to simply ask "GetObjectTypeById(recordId)".
All Answers
Poor I am. I just found out SOSL can have "Id" in fields group. Any other approach?
If you use Schema.getGlobalDescribe(), you may iterate through the returned objects to find the object which has the keyPrefix that matches the leftmost three characters of the ID. If you need this repeatedly, you can use a map<string,string> to map the keyPrefix to the API name, like this:
Once you have keys populated, you can then determine a record's type using keys.get(String.valueOf(recordId).substring(0,3)). This is technically the long way around, but there isn't any way to simply ask "GetObjectTypeById(recordId)".
Thanks fox..this really helps and a much better way. am making this as a global utility method. But I will also have to confirm the heap size and execution statements. Thank you very much.
Schema.sObjectType entityType = idToProccess.getSObjectType();
System.assert(entityType == Opportunity.sObjectType);
source: https://devforce.co/tip-apex-get-sobject-type-from-id/ (https://devforce.co/tip-apex-get-sobject-type-from-id/ )