Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enums: List enumerated values from a Class<? extends Enum>

Tags:

java

enums

I've got the class object for an enum (I have a Class<? extends Enum>) and I need to get a list of the enumerated values represented by this enum. The values static function has what I need, but I'm not sure how to get access to it from the class object.

like image 344
Landon Kuhn Avatar asked Oct 26 '09 19:10

Landon Kuhn


People also ask

Can enum extend enum Java?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

Can a class extend enum?

We cannot extend enum classes in Java. It is because all enums in Java are inherited from java. lang. Enum .

Can enum inherit from another enum Java?

You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.

Which class does all the enum extend?

Which class does all the Enums extend? Explanation: All enums implicitly extend java. lang. Enum.


3 Answers

Class.getEnumConstants

like image 143
Tom Hawtin - tackline Avatar answered Oct 07 '22 21:10

Tom Hawtin - tackline


If you know the name of the value you need:

     Class<? extends Enum> klass = ...       Enum<?> x = Enum.valueOf(klass, "NAME"); 

If you don't, you can get an array of them by (as Tom got to first):

     klass.getEnumConstants(); 
like image 32
Yishai Avatar answered Oct 07 '22 20:10

Yishai


using reflection is simple as calling Class#getEnumConstants():

List<Enum<?>> enum2list(Class<? extends Enum<?>> cls) {
   return Arrays.asList(cls.getEnumConstants());
}
like image 33
dfa Avatar answered Oct 07 '22 22:10

dfa