How to Identify SobjectType Dynamically in Apex

January 25, 2008 admin 0
Here is a script that answers your How to Identify SobjectType Dynamically in Apex

getKeyPrefix of Schema.getGlobalDescribe can be used to identify dynamically the SobjectType in Apex.

String prefix = recordId.substring(0,3);
String objectType;
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
for(Schema.SObjectType s : gd.values()){
if(prefix == s.getDescribe().getKeyPrefix()){
objectType = s.getDescribe().Name;

recordId consists the Id of the sobject Record for whose SobjectType needs to be identified. Above piece of code does it well.