Reputation: 729
Motivation: I would like to construct an enum that represents all possible values for some family of values (I hesitate to say "class" here). The enum will have additional methods, fields, and perhaps even implement other interfaces. I would then like to pass this enum to another method, where it will iterate over all of the possible values (using Enum.values()
and do some work.
I've researched and found that enum Foo
actually becomes Foo extends Enum<Foo>
. This is why I cannot extend an enum. I have tried to define my method arguments as:
myMethod(Class<?> bar) {...}
myMethod(Class<? extends Enum> bar) {...}
myMethod(Class<? extends Enum<?>> bar) {...}
but inside the method when I try something basic like:
int i = bar.values().length;
it fails. Is there some other way I can do this (or avoid the need to do this)?
Note: I could pass an actual instance of the enum and use bar.getDeclaringClass()
to find the enum class (rather than an instance) but this is pretty ugly.
Upvotes: 3
Views: 5837
Reputation: 55223
Try using the following:
<E extends Enum<E>> void myMethod(Class<E> enumType) {
E[] values = enumType.getEnumConstants();
...
}
From the getEnumConstants()
documentation:
Returns the elements of this enum class or null if this Class object does not represent an enum type.
Edit: if you're using different enum types implementing a shared interface, you can modify your method in order to be able to call the interface methods. For example:
interface Fooable {
void foo();
}
...
<E extends Enum<E> & Fooable> void myMethod(Class<E> enumType) {
E[] values = enumType.getEnumConstants();
for (E value : values) {
value.foo();
}
}
Upvotes: 11