How can I get the values of an "enum" in a generic?

Viewed 81

How can I get the values of an "enum" in a generic?

public class Sorter<T extends Enum<?>> {
    public Sorter() {
        T[] result = T.values(); // <- Compilation error
    }
}

On the other hand, I can query the values() for Enum class:

enum TmpEnum { A, B }

public class Tmp {
    void func() {
        T[] result = TmpEnum.values(); // <- It works
    }
}
2 Answers

Class::getEnumConstants

You cannot directly get it from T because generics are erased by the Java compiler so at runtime it is no longer known what T is.

What you can do is require a Class<T> object as constructor parameter. From there you can get an array of the enum objects by calling Class::getEnumConstants.

public class Sorter<T extends Enum<T>> {
    public Sorter(Class<T> clazz) {
        final T[] enumConstants = clazz.getEnumConstants();
    }
}

another way is using interface

public interface Sorter{
    default public void sorting(){
         Sorter[] list=this.getClass().getEnumConstants();
    }
}

use

enum TmpEnum implements Sorter { A, B }
Related