Retrieve Picklist Values In Apex

When crafting highly adaptable code, there are instances where we aim to steer clear of embedding picklist values directly and instead retrieve them dynamically from the field in real-time.

The following code snippet requires two parameters: the Object and the picklist field name. With these inputs, we can retrieve either the Picklist label or the Picklist value (API Name).

String objectName = 'Contact';
String fieldName ='LeadSource';
Schema.SObjectType s = Schema.getGlobalDescribe().get(objectName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
Schema.DescribeFieldResult fieldResult = fields.get(fieldName).getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry pickListVal : ple){
    System.debug(pickListVal.getLabel() +' '+pickListVal.getValue());
}