Say I have an enum which is just
public enum Blah {
A, B, C, D
}
and I would like to find the enum value of a string, for example
Another way of doing this by using implicit static method name()
of Enum. name will return the exact string used to create that enum which can be used to check against provided string:
public enum Blah {
A, B, C, D;
public static Blah getEnum(String s){
if(A.name().equals(s)){
return A;
}else if(B.name().equals(s)){
return B;
}else if(C.name().equals(s)){
return C;
}else if (D.name().equals(s)){
return D;
}
throw new IllegalArgumentException("No Enum specified for this string");
}
}
Testing:
System.out.println(Blah.getEnum("B").name());
//it will print B B
inspiration: 10 Examples of Enum in Java