I have multiple enums in my code:
public enum First { a, b, c, d; }
public enum Second { e, f, g; }
I want to have one method that checks to see if a value is present in any enum using valueOf() without writing one for each enum type. For example (this code does not run):
public boolean enumTypeContains(Enum e, String s) {
try {
e.valueOf(s);
} catch (IllegalArgumentException iae) {
return false;
}
return true;
}
Usage:
enumTypeContains(First,"a"); // returns true
enumTypeContains(Second,"b"); // returns false
Any ideas on how to do something like this?
An enum type is a special data type that enables for a variable to be a set of predefined constants.
EnumUtils class of Apache Commons Lang. The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.
This should work:
public <E extends Enum<E>> boolean enumTypeContains(Class<E> e, String s) {
try {
Enum.valueOf(e, s);
return true;
}
catch(IllegalArgumentException ex) {
return false;
}
}
You then have to call it by
enumTypeContains(First.class, "a");
I'm not sure if simply searching through the values (like in the answer from jinguy) might be faster than creating and throwing an exception, though. This will depend on how often you will get false
, how many constants you have, and how long the stack trace is (e.g. how deep this is called).
If you need this often (for the same enum), it might be better to create once a HashSet or a HashMap mapping the names to the enum values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With