I have to validate a CSV file with a bunch of columns. Some of them need to map to various enum types. I know how to validate string value against a specific enum type, but I would like to have a generic validation method where I would pass in string value and enum type and get validation result. So far I have this:
private boolean valitateSomeSpecificEnum(String value) {
try {
SomeSpecificEnum.valueOf(value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
Is it possible to have something like:
private boolean valitateAgainstTheEnum(String value, Enum<?> theEnum) {
try {
theEnum.valueOf(value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
Note I'm using Enum<?>
in the method signature just to make it clear what I want to achieve, I'm aware that as written it would not work.
Then I could call it like so
valitateTheEnum("foo", SomeSpecificEnum.class);
is this even possible?
Based on the link provided by g00se's in a comment, I've come up with this and it works:
private boolean valitateAgainstTheEnum(String value, Class<? extends Enum> theEnum) {
try {
Enum.valueOf(theEnum, value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
Only question remains if there is a more elegant way to do it