function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

load generic Sobject with only ID

Hi There,


I'm sure this must be simple, but I'm not finding an immediate solution anywhere.


I have a method with ID as input parameter but no idea what object the ID is for.


I want to work out what type of object is is before I decide what to do with it.


sObject generic = [select ID from [?] where id=:someid];


Sorry for the basic question.




Here's one option that might work for you, this is code that executes in a System Log window, but should be easy to convert to a class method.



// Load a contact into a generic sObject just so we have a valid ID.
sObject testObject = [SELECT Id FROM Contact LIMIT 1];
// Get the first three characters of the ID, these are the object's prefix.
String objectKey = String.valueOf( testObject.Id ).toLowerCase().subString( 0, 3 );
String objectName = '';
// Loop through all objects and match their prefixes against our ID's prefix.
for ( Schema.SObjectType objectType : Schema.getGlobalDescribe().values() )
    // Get meta-data for the current object.
    Schema.DescribeSObjectResult objInfo = objectType.getDescribe();
    // Compare the object's prefix against our ID's prefix.
    if ( objInfo.getKeyPrefix() == objectKey )
        // Found a match, save the object name and break out of the loop.
        objectName = objInfo.getName();

// Output the name of the associated object.
System.debug( objectName );