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

user3429660 :

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
    }
}
Jan Thomä :

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();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=120941&siteId=1