Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic class of enum, number of values

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.

like image 762
ratatosk Avatar asked Dec 10 '25 13:12

ratatosk


2 Answers

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.

like image 189
Paul Bellora Avatar answered Dec 12 '25 02:12

Paul Bellora


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];
  }
like image 44
AlexR Avatar answered Dec 12 '25 03:12

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!