How to find object type from Salesforce record id?

How to find object type from Salesforce record id?

Sample Code to execute in Developer Console:

Id myId = '0035A00003MuvnuQAB';  
String sObjName = myId.getSObjectType().getDescribe().getName();  
system.debug('Object Name is ' + sObjName);  

Output:

( Or )

Sample Code:

Visualforce page:

<apex:page Controller="sample" sidebar="false" >  
  
<apex:form >  
  
    <apex:pageblock id="pg" >  
  
        <apex:pageblockSection >  
  
            <apex:pageBlockSectionItem >Record Id</apex:pageBlockSectionItem>  
            <apex:pageblockSectionItem ><apex:inputtext value="{!recId}" /></apex:pageblockSectionItem>  
  
        </apex:pageblockSection>  
  
        <apex:pageBlockButtons >  
  
            <apex:commandButton value="Find" action="{!find}" reRender="pg"/>  
  
        </apex:pageBlockButtons>  
  
        <apex:outputText >The object type is : {!objType}</apex:outputText>  
  
    </apex:pageblock>  
  
</apex:form>     
  
</apex:page>  

Apex: Controller:

public with sharing class sample {  
  
    public Id recId {get;set;}  
    public String output {get;set;}  
    public Schema.SObjectType objType {get;set;}  
      
    public void find() {  
  
        objType = recId.getSobjectType();  
        System.debug('Object Type is ' + objType);  
  
    }  
  
} 

Output:

Leave a Reply