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?
Here is your solution:
It gets all of the enum’s vaules and checks to see if it has a value that shares a name with the parameter you passed in. If so, then it returns true, otherwise it returns false.
This has been tested and works. Test code:
Prints: