To access the token for a field, use one of the following methods:
The field token uses the data type Schema.SObjectField.
In the following example, the field token is returned for the Account object's Description field:
Schema.SObjectField fieldToken = Account.Description;
In the following example, the field token is returned from the field describe result:
// Get the describe result for the Name field on the Account object Schema.DescribeFieldResult dfr = Schema.sObjectType.Account.fields.Name; // Verify that the field token is the token for the Name field on an Account object System.assert(dfr.getSObjectField() == Account.Name); // Get the describe result from the token dfr = dfr.getSObjectField().getDescribe();
To access the describe result for a field, use one of the following methods:
The field describe result uses the data type Schema.DescribeFieldResult.
The following example uses the getDescribe method:
Schema.DescribeFieldResult dfr = Account.Description.getDescribe();
This example uses the fields member variable method:
Schema.DescribeFieldResult dfr = Schema.SObjectType.Account.fields.Name;
In the example above, the system uses special parsing to validate that the final member variable (Name) is valid for the specified sObject at compile time. When the parser finds the fields member variable, it looks backwards to find the name of the sObject (Account) and validates that the field name following the fields member variable is legitimate. The fields member variable only works when used in this manner.
For more information about the methods available with a field describe result, see DescribeFieldResult Class.
Use the field describe result's getMap method to return a map that represents the relationship between all the field names (keys) and the field tokens (values) for an sObject.
The following example generates a map that can be used to access a field by name:
Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Account.fields.getMap();
The map has the following characteristics:
For example, if the code block that generates the map is in namespace N1, and a field is also in N1, the key in the map is represented as MyField__c. However, if the code block is in namespace N1, and the field is in namespace N2, the key is N2__MyField__c.
In addition, standard fields have no namespace prefix.
Note the following when describing fields.