Reputation: 2732
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
}
}
Upvotes: 6
Views: 105
Reputation: 13630
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();
}
}
Upvotes: 8
Reputation: 616
another way is using interface
public interface Sorter{
default public void sorting(){
Sorter[] list=this.getClass().getEnumConstants();
}
}
use
enum TmpEnum implements Sorter { A, B }
Upvotes: 0