2

I have a generic class with enum type as generic, and I want to iterate through all elements in the enum. Hope the following example (not working) will make more clear what I want. What is the correct syntax?

public class GenericClass<T extends Enum<T>>{

    T myEnum;

    public void doSomething(){
        for(T element : myEnum.values()){// <-- values() not available
            ....
        }
    }
}

I would use the class this way

GenericClass<OtherClass.MyEnumType> manager;
manager.doSomething();
holap
  • 438
  • 2
  • 18
  • @ohlmar yes, it doesn't work that way. I can't see values(). – holap Feb 18 '14 at 13:29
  • Explain, why you want to use an `Enum` instead of maybe just a `List`? Give some more information about what you want to achieve! Since `Enum` is not an array, `myEnum` is also no array and you can't loop over one `Enum` value! – bobbel Feb 18 '14 at 13:31
  • You can't see `values()` because class `Enum` is not the same as an `enum` (as opposed to `class`). – Smutje Feb 18 '14 at 13:35

3 Answers3

2

You're attempting to hold a reference to an instance of an enum which isn't very useful, but you can require that the enum class is passed to the constructor (called a type token).

With a class, you can use the (typed) class method getEnumConstants() (which returns null if the class isn't an enum class, but we've bound it to be an enum class).

This compiles:

public class GenericClass<T extends Enum<T>> {

    Class<T> enumClass;

    public GenericClass(Class<T> enumClass) {
        this.enumClass = enumClass;
    }

    public void doSomething() {
        for (T element : enumClass.getEnumConstants()) {

        }
    }
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

Not really possible. values() method is not part of the Enum class but of a class derived by the compiler from your enum: public class YourEnum extends Enum<YourEnum>.

See this SO question for more info: How is values() implemented for Java 6 enums?

Community
  • 1
  • 1
dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
1

this is equivalent to the static values() method:

T[] items = myEnum.getDeclaringClass().getEnumConstants();

See Enum.getDeclaringClass()

(Basically this returns the class defining the enum item, which may or may not be == myEnum.getClass(), depending on whether or not the enum item has a body)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588