Salesforce allows you to describe sObjects either by using sObject or field tokens, or the describeSObjects Schema method.

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

  • Token — a lightweight, serializable reference to an sObject or a field that is validated at compile time. This is used for token describes.
  • The describeSObjects method — a method in the Schema class that performs describes on one or more sObject types.
  • Describe result — an object of type Schema.DescribeSObjectResult that contains all the describe properties for the sObject or field. Describe result objects are not serializable, and are validated at runtime. This result object is returned when performing the describe, using either the sObject token or the describeSObjects method.

The following code provides a general example of how to use tokens and describe results to access information about sObject and field properties:

// Create a new account as the generic type sObject
sObject s = new Account();

// Verify that the generic sObject is an Account sObject
System.assert(s.getsObjectType() == Account.sObjectType);

// Get the sObject describe result for the Account object
Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe();

// Get the field describe result for the Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;

// Verify that the field token is the token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);

// Get the field describe result from the token
f = f.getSObjectField().getDescribe();

As an alternative to using tokens, you can describe sObjects by calling the describeSObjects Schema method and passing one or more sObject type names for the sObjects you want to describe. Using this method, you can describe up to 100 sObjects.

This example gets describe metadata information for two sObject types — The Account standard object and the Contact standard object. After obtaining the describe result for each sObject, this example writes the returned information to the debug output, such as the sObject label, number of fields, and the number of child relationships.

// sObject types to describe
String[] types = new String[]{'Account','Contact'};

// Make the describe call
Schema.DescribeSobjectResult[] results = Schema.describeSObjects(types);

System.debug('Got describe information for ' + results.size() + ' sObjects.');

// For each returned result, get some info
for(Schema.DescribeSobjectResult res : results) 
    System.debug('sObject Label: ' + res.getLabel());
    System.debug('Number of fields: ' + res.fields.getMap().size());

    // Get child relationships
    Schema.ChildRelationship[] rels = res.getChildRelationships();
    System.debug(res.getName() + ' has ' + rels.size() + ' child relationships.');

Useful Documentation