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
}
}
Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Enum, Interfaces, and GenericsThe enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation.
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
Inheritance Is Not Allowed for Enums.
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();
}
}
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