If I pass to a method, or store in a variable, a collection of classes that I know are all Enums (ideally guaranteed, but I don't mind casting), is there a way to let the compiler know they are enum classes, in order to use methods like values()
, EnumSet.allOf()
, etc? I.e., I'm looking at cases where I cannot refer to the names of the Enum classes directly.
I believe this is not possible, but wanted to verify.
An example might look something like this:
enumClasses.stream()
.map(eclass -> EnumSet.allOf(eclass))
... more here...
but I don't see a way to prove in the declaration of enumClasses (as variable or parameter) that it's only enums.
Examples: Some cases I tried that did not work using Class<? extends Enum<?>>>
List<? extends Class<? extends Enum<?>>> enums = List.of(MyEnum.class);
enums.forEach(eclass -> EnumSet.allOf(eclass)); // error here.
or
Class<? extends Enum<?>> enumClass = MyEnum.class;
EnumSet.allOf(enumClass); // error here.
enumClass.values(); // error here.
I also tried creating this helper-method signature:
static <E extends Enum<E>> EnumSet myValues(Class<E> iEnumClass) {
return EnumSet.allOf(iEnumClass);
}
and the method compiles fine, but I have the same problems as above when I try to call the method (unless I call that method directly with the class-name, like myValues(MyEnum.class)
)