Someone
Someone

Reputation: 551

Get enum values from Enum object

If I were to declare an enum like so

public enum Foo {A, B, C}

then I can get the enum values using

Foo[] values = Foo.values();

However if I wanted to pass Foo as a generic type, like so, I can't get the values since it's generic.

class Bar<E extends Enum<E>> {

    public Bar(E e) {
        E[] values = e.values(); // not possible
    }

}

Is it possible to iterate over the enum values any other way?

Upvotes: 1

Views: 169

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198471

You'll have to pass the Class object:

 public Bar(Class<E> clazz) {
    E[] values = clazz.getEnumConstants();
 }

...or, if you have one element e of the enum, you might be able to use e.getDeclaringClass().getEnumConstants(). (Don't use e.getClass().getEnumConstants(), which won't work if your enum constants define their own constant-specific methods.)

Another option: EnumSet.allOf(clazz), which is actually more efficient than clazz.getEnumConstants() in many ways, since it's O(1) and not O(n) in the number of enum constants.

Upvotes: 7

Related Questions