3

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().

rozina
  • 4,120
  • 27
  • 49
  • What should noneOf() do? What's the first argument for? – JB Nizet Dec 22 '16 at 12:26
  • @JBNizet It does not matter for the question. Maybe I should have given the method a more random name. – rozina Dec 22 '16 at 12:41
  • 2
    @rozina it does matter, because your question is currently unclear. Please add more information about what you're actually trying to do. – Andy Turner Dec 22 '16 at 12:42
  • 1
    "get the Foo.class from the variable enumSet inside fooBar() function." You can only do that if `enumSet` is non-empty: `enumSet.iterator().next().getClass()`. If it's empty, you're stuck. (And that also doesn't quite work if the first enum element in the set defines a class body). – Andy Turner Dec 22 '16 at 12:44
  • maybe http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime?rq=1 –  Dec 22 '16 at 12:44

1 Answers1

3

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();
}
hoat4
  • 1,182
  • 12
  • 9