I have two enums that implement a common interface. I've tried to declare the interface so only enums can implement it.
interface CommonEnumInterface<E extends Enum<?>> {
/** It doesn't matter what this does. */
E commonInterfaceMethod();
}
enum Enum1 implements CommonEnumInterface<Enum1> {
FOO,
BAR,
BAZ;
@Override
public Enum1 commonInterfaceMethod() {
return null;
}
}
enum Enum2 implements CommonEnumInterface<Enum2> {
BLAH,
YADDA,
RHUBARB;
@Override
public Enum2 commonInterfaceMethod() {
return Enum2.BLAH;
}
}
Now I want to declare a generic type parameter that extends CommonEnumInterface
, which should imply the generic type is also an enum:
class CreatingGenericEnumSet<E extends Enum<E> & CommonEnumInterface<E>> {
CreatingGenericEnumSet() {
// Is it possible to instantiate an EnumSet of a generic type?
EnumSet<E> enumSet = EnumSet.noneOf(E.class); // Illegal class literal
// According to a comment by @tackline, this is illegal, too.
Collection<E> hackyVariable = Collections.emptyList();
EnumSet<E> jankyWay = EnumSet.copyOf(hackyVariable);
}
}
My question is in the comments above. Is there a way, preferably in one line, to declare an EnumSet of a generic type?
Is this the right way to declare the interface and type parameters?
class CreatingGenericEnumSet<E extends Enum<E> & CommonEnumInterface<E>> {
CreatingGenericEnumSet(Class<E> enumClass) {
EnumSet<E> enumSet = EnumSet.<E>noneOf(enumClass);
}
}
similar question can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With