Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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
    }
}
like image 728
user3429660 Avatar asked Jun 21 '19 11:06

user3429660


People also ask

How do you find the value of an enum?

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.

Can enums be generic?

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.

Can you use == for enums?

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.

Can you inherit enum?

Inheritance Is Not Allowed for Enums.


1 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();
    }
}
like image 100
Jan Thomä Avatar answered Oct 19 '22 03:10

Jan Thomä