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.