Iterate enum values using java generics
For completeness, JDK8 gives us a relatively clean and more concise way of achieving this without the need to use the synthethic values()
in Enum class:
Given a simple enum:
private enum TestEnum {
A,
B,
C
}
And a test client:
@Test
public void testAllValues() {
System.out.println(collectAllEnumValues(TestEnum.class));
}
This will print {A, B, C}
:
public static <T extends Enum<T>> String collectAllEnumValues(Class<T> clazz) {
return EnumSet.allOf(clazz).stream()
.map(Enum::name)
.collect(Collectors.joining(", " , "\"{", "}\""));
}
Code can be trivially adapted to retrieve different elements or to collect in a different way.
This is a hard problem indeed. One of the things you need to do is tell java that you are using an enum. This is by stating that you extend the Enum class for your generics. However this class doesn't have the values() function. So you have to take the class for which you can get the values.
The following example should help you fix your problem:
public <T extends Enum<T>> void enumValues(Class<T> enumType) {
for (T c : enumType.getEnumConstants()) {
System.out.println(c.name());
}
}
Another option is to use EnumSet:
class PrintEnumConsants {
static <E extends Enum <E>> void foo(Class<E> elemType) {
for (E e : java.util.EnumSet.allOf(elemType)) {
System.out.println(e);
}
}
enum Color{RED,YELLOW,BLUE};
public static void main(String[] args) {
foo(Color.class);
}
}