I suggest to use an util-method like @Phil Anderson
mentioned. I would only change it to a general pattern:
public static <T extends Enum<T>> void some_method(Class<T> clazz, String name) {
try {
T foundEnum = Enum.valueOf(clazz, name);
// name matches to one of enum values, do something with it
} catch (IllegalArgumentException e) {
// name doesn't matches to any of enum values
}
}
which in case of contains semantic could look like this:
public static <T extends Enum<T>> boolean contains(Class<T> clazz, String name) {
try {
Enum.valueOf(clazz, name);
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
Updated:
As @phil-anderson
mentioned, from performance point of view this method have certain disadvantages, because generation and throwing of exception is pretty slow (see How slow are Java exceptions?). But this is only a case, if method is invoked with an incorrect name
value.
So, in this case you could use this pattern:
public static <T extends Enum<T>> void some_method(Class<T> clazz, String name) {
for (T each : clazz.getEnumConstants()) {
if (each.name().equals(name)) {
// name matches to one of enum values, do something with it
}
}
// name doesn't matches to any of enum values
}
Moreover, if performance plays an important role, especially if enum consists of large number of values, it is not efficient to iterate over (maybe) all of them. The solution could be using a lazy hash map for enums and get the value by a hashcode. For example:
@SuppressWarnings("unchecked")
public static <T extends Enum<T>> void some_method(Class<T> clazz, String name) {
Map<String, Enum<?>> enumMap = enumsMap.get(clazz);
if (enumMap == null) {
enumMap = new HashMap<String, Enum<?>>();
for (T t : clazz.getEnumConstants()) {
enumMap.put(t.name(), t);
}
enumsMap.put(clazz, enumMap);
}
T t = (T) enumMap.get(name);
if (t != null) {
// name matches to one of enum values, do something with it
} else {
// name doesn't matches to any of enum values
}
}