I\'m trying to find a way to iterate through an enum\'s values while using generics. Not sure how to do this or if it is possible.
The following code illustrates
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 > String collectAllEnumValues(Class 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.