Accessing custom labels dynamically in Apex


Upon reading this blog, you will gain the ability to:

  • Access custom labels dynamically in Apex.
  • Access custom labels dynamically in Apex for a specific language.
  • And discover many other valuable insights.

Apex Script to Access Custom Labels Dynamically

Salesforce has released following option:

System.Label.get(namespace, label, language)

To access the Developer Console, click on Setup, and then select “Developer Console.” In the Developer Console, I will utilize the “Execute Anonymous Apex” tool to run the Apex code.

An “anonymous block” in Apex refers to a code segment that is not stored in the metadata but can be compiled and executed. These blocks execute with the permissions of the current user and may fail to compile if they violate the user’s object or field-level permissions.

To open the “Execute Anonymous” window, click on “Debug” and choose “Open Execute Anonymous Window.” This window allows you to execute anonymous Apex code snippets.

//Without Namespace, you can pass namespace in first paramter
System.debug(System.Label.get('', 'confirmationMessage', 'fr'));
//If you do not pass language value, then it will pick default one:
system.debug(System.Label.get('', 'Heading', ''));

To execute all the code in the window, click on the “Execute” button. Ensure that you have selected the “Open Log” checkbox. After executing the code, the log will automatically open in the Log Inspector.

The debug log will be listed on the Logs tab. You can double-click the log to open it in the Log Inspector. In our case, the log will open automatically after the code execution. For a more detailed analysis of the variables’ runtime values, remember to select the “Debug Only” checkbox, as illustrated in the provided screenshot.