How to get the sObject type from a controller?

try:

public class myControllerExtension {

    public myControllerExtension(ApexPages.StandardController stdController) {
        String type = stdController.getRecord().getSObjectType().getDescribe().getName();

    }
}

You can't get the object type from sObjectType as an string. Try by using getDescribe().getName();

Apex provides two data structures for sObject and field describe information:

  • Token—a lightweight, serializable reference to an sObject or a field that is validated at compile time.

  • Describe result—an object that contains all the describe properties for the sObject or field. Describe result objects are not serializable, and are validated at runtime.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_describe_objects_understanding.htm


There are a couple of approaches you can use for this, one is using SObjectType, the other is using the 'instanceof' feature in Apex. Using 'instanceof' is more natural from an OOP perspective, and thus Java and C# developers will understand it more than the SObjectType approach. The first depends if you plan to do any Apex Describe type work after, thus the SObjectType is the place to start if so.

     SObjectType sObjectType = controller.getRecord().getSObjectType();
     if(sObjectType == Opportunity.sObjectType)
     {
        // This is a Opportunity record
        Opportunity opp = (Opportunity) controller.getRecord();
     }
     else if(sObjectType == Account.sObjectType)
     {
        // This is a Account record             
        Account acc = (Account) controller.getRecord();
     }


     SObject record = controller.getRecord();
     if(record instanceof Opportunity)
     {
        // This is a Opportunity record
        Opportunity opp = (Opportunity) controller.getRecord();             
     }
     else if(record instanceof Account)
     {
        // This is a Account record             
        Account acc = (Account) controller.getRecord();             
     }

Easy!!

public YourExtension(ApexPages.StandardController controller) {
  String sObjectType = String.valueOf(controller.getRecord().getSObjectType());
}