How do I find out, how many values my enum has in this example:
public class Analyser<C extends Enum<C>>{
private long[] dist;
public Analyser() {
super();
dist = new long [C.getEnumConstants().length];
}
}
The last line does not work.
You need to pass in the class literal of the enum:
public Analyser(Class<C> enumType) {
super();
dist = new long [enumType.getEnumConstants().length];
}
...
Analyser<MyEnum> analyser = new Analyser(MyEnum.class);
This is because C has no meaning at runtime due to type erasure.
I guess the last line cannot be compiled. You need Class instance to do this. Here is a modified version of your code:
public class Analyser<C extends Enum<C>>{
private long[] dist;
public Analyser(Class<C> clazz) {
super();
dist = new long [clazz.getEnumConstants().length];
}
}
I however cannot exactly understand why do you extends your class from Enum. If you know the enum class at development time you can just say MyEnum.values().length.
If you want to write generic code that checks how many values does any enum have you can just write an utility method like:
public static int enumSize(Class<C extends Enum<C>> clazz) {
return clazz.getEnumConstants().length];
}
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