0

I am trying to match a string (normally provided as an input parameter) to a field of an enum:

public class Main {
    public static void main(String[] args) {
        String input = "AlternativeName1";

        switch (input) {
            case Algorithm.ALG1.alternativeName:
                break;
            case Algorithm.ALG2.alternativeName:
                break;
        }
    }

    public enum Algorithm {
        ALG1("AlternativeName1"),
        ALG2("AlternativeName2");

        public final String alternativeName;

        Algorithm(String alternativeName) {
            this.alternativeName = alternativeName;
        }
    }
}

The compiler complains that it expects a constant expression after the 'case' statement, but I don't think it gets any more constant than public final String.

So how can I check the input string against a predefined list of enum fields?

I can think of an equivalent if-statement but I want to make sure to always check against all defined enum members which is what 'switch' (together with Intellij) can guarantee.

inorik
  • 147
  • 9
  • 1
    A constant String would be a **static** final variable. Just loop over your enum values and find the one with the searched alternativeName. This method should be in the enum itself, BTW. – JB Nizet Apr 15 '17 at 15:14
  • These aren't compile time constant. They are instance fields, whose value is not assigned until the enum value instance is constructed. – Andy Turner Apr 15 '17 at 15:15
  • Thanks, I understand the error now. Is there any way to give every enum entry its own compile time constant 'alternativeName'? Otherwise, I'll go with @JBNizet solution. – inorik Apr 15 '17 at 15:27

0 Answers0