holap
holap

Reputation: 438

using enum (as type) in generic class and looping through its elements

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

Upvotes: 2

Views: 346

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298878

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)

Upvotes: 1

Bohemian
Bohemian

Reputation: 425003

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

        }
    }
}

Upvotes: 2

dcernahoschi
dcernahoschi

Reputation: 15240

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?

Upvotes: 1

Related Questions