This post will discuss how to dynamically read the value of a constant in Java.

1. Using Reflection

This can be achieved using Reflection in Java, which allows programmatic access to information about the fields of loaded classes. Note that this approach is not recommended, and we should avoid reflection at all costs.

Download  Run Code

Output:

NUM_1 has a value of ONE
NUM_2 has a value of TWO
NUM_3 has a value of THREE
NUM_4 has a value of FOUR
NUM_5 has a value of FIVE

2. Using Enum

The recommended solution is to use Enum for storing constants, as shown below:

Download  Run Code

Output:

NUM_1 has a value of ONE
NUM_2 has a value of TWO
NUM_3 has a value of THREE
NUM_4 has a value of FOUR
NUM_5 has a value of FIVE

3. Using Map

Finally, we can use a map with constant’s variable names as keys against their values.

Download  Run Code

Output:

NUM_1 has a value of ONE
NUM_2 has a value of TWO
NUM_3 has a value of THREE
NUM_4 has a value of FOUR
NUM_5 has a value of FIVE

That’s all about dynamically reading the value of a constant in Java.