I’m trying to access properties of an arbitrary Enum from inside a generic Java class. In particular, I’d like to access the number of values in the Enum as well as the actual values themselves.
This (obviously silly) dummy code illustrates the intent:
public class Test <E extends Enum>{
public enum TestEnum {
FIRST, SECOND, THIRD
}
public Test() {
System.out.println(E.values().length); //error - won't compile
}
public static void main(String[] args) {
Test<TestEnum> t = new Test<TestEnum>();
}
}
There are some solutions to similar problems here on StackOverflow, but they require modifying the Enum. It’s important here that the code work for any arbitrary Enum.
Is this even possible in Java?
Thank you in advance for any possible advice.
~Chris
You can use reflection and the static values method the compiler automatically adds when it creates an enum.