I have this enum below:
public enum TestEnum {
h1, h2, h3, h4;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
System.out.println(TestEnum.h1.name());
String ss = "h3";
try {
TestEnum.valueOf(ss); // but this validates with all the enum values
System.out.println("valid");
} catch (IllegalArgumentException e) {
System.out.println("invalid");
}
}
}
I need to check if the enum value represented by my string ss
is one of my enum values h1
, h2
or h4
. So if h3
is being passed as a string, I would like to return false or throw IllegalArgumentException
. I won't need to validate ss
with h3
in the enum.
I came up with the below code to do this with the enum, but I believe there is a more elegant solution.
public enum TestEnum {
h1, h2, h3, h4;
public static boolean checkExcept(String el, TestEnum... except){
boolean results = false;
try{
results = !Arrays.asList(except).contains(TestEnum.valueOf(el));
}catch (Exception e){}
return results;
}
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
String ss = "h3";
if(TestEnum.checkExcept(ss,TestEnum.h1, TestEnum.h2, TestEnum.h3)){
System.out.println("valid");
}else{
System.out.println("invalid");
}
}
}
Is there any better way of solving this problem?