How to find object type from Salesforce record id?

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:



Cheers!!!

3 comments: