Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating EnumSets of generic types

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?

like image 348
Michael Scheper Avatar asked Jan 10 '14 03:01

Michael Scheper


1 Answers

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

like image 122
sasankad Avatar answered Oct 18 '22 11:10

sasankad