rozina
rozina

Reputation: 4232

Get class of EnumSet's Enum

Is it possible to get the class of the Enum from a variable of type EnumSet.

Consider the following code:

enum Foo
{
    FOO_0,
    FOO_1,
}

<E extends Enum<E>> void fooBar(EnumSet<E> enumSet, Class<E> type)
{
    EnumSet<E> none = EnumSet.noneOf(type);
    // ...
}

void bar()
{
    EnumSet<Foo> enumSet = EnumSet.of(Foo.FOO_1);
    fooBar(enumSet, Foo.class);
}

Writing Foo.class in fooBar() seems redundant. I would like to extract the class from the enumSet inside fooBar() function. Is that even possible?

What I wish to do is just call fooBar(enumSet); and still be able to instantiate the none variable as EnumSet.noneOf().

Upvotes: 4

Views: 668

Answers (1)

hoat4
hoat4

Reputation: 1212

Works for empty EnumSets also, and returns the correct enum type even when the element has a class body:

public static <T extends Enum<T>> Class<T> getElementType(EnumSet<T> enumSet) {
    if (enumSet.isEmpty())
        enumSet = EnumSet.complementOf(enumSet);
    return enumSet.iterator().next().getDeclaringClass();
}

Upvotes: 3

Related Questions