Reputation: 131
One of the methods I am currently writing for my Java library takes an array of an arbitrary enumeration type as its sole argument. If any of these is non-null, I can access the instance of java.lang.Class
representing that enumeration type, which may or may not be a public type. (If they are all null, there is no purpose to this anyway under the circumstances.) How do I get the number of possible values that enumeration type has? The approach I am currently using - Array.getLength(clazz.getMethod("values").invoke(null));
- fails when the Enum class is not public. How do I fix this?
Upvotes: 1
Views: 781
Reputation: 37655
The easiest way to get an array of enum constants from a Class
object is
clazz.getEnumConstants();
To find the number of enum constants you can add .length
to this.
If you want to get the array of enum constants from an instance of an enum, it is important to do
e.getDeclaringClass().getEnumConstants();
rather than
e.getClass().getEnumConstants();
The reason for this is demonstrated by the following example:
private enum Colour {
WHITE,
BLUE {
@Override
public String toString() {
return "blue";
}
}
}
public static void main(String[] args) throws Exception {
System.out.println(Arrays.toString(Colour.BLUE.getClass().getEnumConstants()));
System.out.println(Arrays.toString(Colour.WHITE.getClass().getEnumConstants()));
System.out.println(Arrays.toString(Colour.BLUE.getDeclaringClass().getEnumConstants()));
}
This program outputs
null
[WHITE, blue]
[WHITE, blue]
What is going on here is that in order to override the method toString
for the BLUE
constant, a subclass of Colour
is created. This means that Colour.BLUE.getClass()
does not return Colour.class
, so Colour.BLUE.getClass().getEnumConstants()
returns null
. This issue does not apply for WHITE
because WHITE
does not require an extra class.
Upvotes: 1