How would the following method that happens to be named reverse
be rewritten as a generic method that allows any enumerated type.
public class TestX {
enum Gender { male, female }
public static void main(String[] args) {
System.out.printf("%s\n", TestX.reverse("male").name());
System.out.printf("%s\n", TestX.reverse("female").name());
}
static Gender reverse(String name) {
for (Gender g: Gender.class.getEnumConstants())
if (g.name().equals(name))
return g;
return null;
}
}
What I tried (but does not compile at T.class
):
<T extends Enum<?>> T reverse2(String name) {
for (T t: T.class.getEnumConstants())
if (t.name().equals(name)) return t;
return null;
}
How about
// Every enum class extends Enum<ThisEnumClassName>.
// Since we want T to be enum we must write it as "extends Enum"
// but Enum is also generic and require type of store parameters
// so we need to describe it as Enum<T> which finally gives us - T extends Enum<T>
static <T extends Enum<T>> T reverse(String name, Class<T> clazz) {
for (T t : clazz.getEnumConstants())
if (t.name().equals(name))
return t;
return null;
}
If you want to make it generic you need specify from which Enum you want to get your values. Otherwise there is no way to find correct enym (unless you also put it somewhere in name
like full.package.name.of.YourEnum.VALUE
).
You can also consider using
Enum.valueOf(YourEnumClass.clazz, "ENUM_FIELD_NAME")
but this approach instead of returning null
when enum will not have specified element will throw java.lang.IllegalArgumentException
.
I believe that the following would work:
static <T extends Enum<T>> T reverse(String name, Class<T> t_class) {
for (T t: t_class.getEnumConstants())
if (t.name().equals(name))
return t;
return null;
}
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