Describe sObject using Apex

Describing the object

This code snippet example will populate Account object information as a JSON string.

//1.Generate token
Account acc = new Account();
Schema.SObjectType obj = acc.getSObjectType();
System.debug(obj);

//2.Obtain the describe information
Schema.DescribeSObjectResult objResults = obj.getDescribe();
System.debug(JSON.serialize(objResults));

JSON output


Describing a field in a sObject

Below code snippet will describe the Account's Name field

Schema.sObjectField field = Account.Name;
Schema.DescribeFieldResult fieldResult = field.getDescribe();
System.debug(fieldResult);

Output


Schema.DescribeFieldResult[getByteLength=765;getCalculatedFormula=null;getCompoundFieldName=Name;getController=null;getDefaultValue=null;getDefaultValueFormula=null;getDigits=0;getFilteredLookupInfo=null;getInlineHelpText=null;getLabel=Account Name;getLength=255;getLocalName=Name;getMask=null;getMaskType=null;getName=Name;getPrecision=0;getReferenceTargetField=null;getRelationshipName=null;getRelationshipOrder=null;getScale=0;getSoapType=STRING;getSobjectField=Name;getType=STRING;isAccessible=true;isAggregatable=true;isAutoNumber=false;isCalculated=false;isCascadeDelete=false;isCaseSensitive=false;isCreateable=true;isCustom=false;isDefaultedOnCreate=false;isDependentPicklist=false;isDeprecatedAndHidden=false;isDisplayLocationInDecimal=false;isEncrypted=false;isExternalId=false;isFilterable=true;isGroupable=true;isHighScaleNumber=false;isHtmlFormatted=false;isIdLookup=false;isNameField=true;isNamePointing=false;isNillable=false;isPermissionable=false;isQueryByDistance=false;isRestrictedDelete=false;isSearchPrefilterable=false;isSortable=true;isUnique=false;isUpdateable=true;isWriteRequiresMasterRead=false;]

Further you can get more information using the above properties of Name field in Account Object.


System.debug(fieldResult.getType());

Output: STRING

Also you can get All the fields in Account object as a map and get describe the fields one by one using the field name as the key.


Map<String, Schema.SObjectField> fieldMap = Schema.sObjectType.Account.fields.getMap();
System.debug(fieldMap.get('Name').getDescribe().getType());


Comments

Popular Posts