function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Field Labels

I'm trying to figure out how to access the labels for specific fields in a custom object.  The following code works great for this:
String mylabel = Schema.SObjectType.SFDC_Target_Company__c.fields.Analyst__c.getLabel();

The issue is that the field that I want to get the label for is variable.  So I want to have more of a lookup function to get the label.  Trying
String analyst = 'Analyst__c';
String mylabel = Schema.SObjectType.SFDC_Target_Company__c.fields.analyst.getLabel();

Does not work, since it does not pull 'Analyst__c' from the variable analyst.  I tried getting all of the fields from my object so I could cycle through and compare the field name, then pull the label out of the correct one, but Field is apparently an invalid type. 

How can I find the label for these fields? 

For reference, below is a snippet of my code that shows how I'm getting the fields that I need labels for (it's for history tracking):

Public List<List<SFDC_Target_Company__History>> listHistory {
   if(listHistory == null){
 listHistory = new List<List<SFDC_Target_Company__History>>();
 List<SFDC_Target_Company__History> tempHistory = new List<SFDC_Target_Company__History>();
 for(ID i : projects.keySet()){
  tempHistory = [select ParentId,Field,NewValue,OldValue,CreatedDate, Parent.Name  from SFDC_Target_Company__History where ParentId = :i and Field != 'created' Order by CreatedDate desc];
    return listHistory;



You might be able to access the field by using the variable as a map key.  I don't have confidence that this is the best answer, but it might help.
Map<String, Schema.SObjectField> M = Schema.SObjectType.Object.fields.getMap();
String s1 = 'Analyst__c';
SObjectField f = M.get(s1);
String label = f.getLabel();


Some relevant documentation:


Thanks for the reply, I just had to make one small change to the code you provided and it worked great:

String label = f.getDescribe().getLabel();

Thanks for your help!