How to access constants from a java class through other variable?

I have java class which has all constants as given below:

public final class CategoryIDs {

  public static final String Extraction_of_natural_gas = "1111";
  public static final String Mining_of_hard_coal = "2222";
  public static final String Mining_of_iron_ores = "3333";
  public static final String Mining_of_lignite = "4444";

}

Now I want to access these constants in some other class through a variable which holds name of the variable.

For example:

String temp = "Extraction_of_natural_gas";

Using this temp variable I want to access constants from above class. But I can't do CategoryIDs.temp as it isn't allowed. So what is the best way to achieve this?

Jon Skeet
people
quotationmark

If you really, really need to do this with your current structure, you could use reflection.

However, you may well find that an enum would be a better fit. Something like:

public enum CategoryID {

    EXTRACTION_OF_NATURAL_GAS("Extraction_of_natural_gas", 1111),
    MINING_OF_HARD_COAL("Mining_of_hard_coal", 2222),
    MINING_OF_IRON_ORES("Mining_of_iron_ores", 3333),
    MINING_OF_LIGNITE("Mining_of_lignite", 4444);

    private static final Map<String, CategoryID> keyMap;

    static {
        keyMap = new HashMap<>();
        for (CategoryID category : CategoryID.values()) {
            keyMap.put(category.getKey(), category);
        }
    }

    private final String key;
    private final int value;

    public int getValue() {
        return value;
    }

    public String getKey() {
        return key;
    }

    private CategoryID(String key, int value) {
        this.key = key;
        this.value = value;
    }

    public static CategoryID fromKey(String key) {
        return keyMap.get(key);
    }
}

Benefits of this approach:

  • You separate the name in the code (which is now more conventional for Java) from the key you'd provide in the data. That means you can use whatever keys you'd like in the data, including ones with spaces in etc. They no longer need to be valid identifiers.
  • You still get compile-time safety when you refer to the enum values from code.
  • You get better safety as you'll never accidentally use a string instead of a category ID, which you could easily have done using your constants.

people

See more on this question at Stackoverflow