简体   繁体   中英

How do I write a generic for loop for a Java Enum?

Is there a way to write a generic loop to iterate over an arbitrary Enum? For example:

public static void putItemsInListBox(Enum enum, ListBox listbox){
    for(Enum e : enum.values(){
        listBox.addItem(e.toString(), String.valueOf(e.ordinal());
    }
}

You can not do the above, because the Enum class does not have a method called values() like the implemented Enum classes. The above for loop works fine for a class that is defined as an enum.

It works exactly the same way as if the Class is passed:

public static <E extends Enum<?>> void iterateOverEnumsByInstance(E e)
{
    iterateOverEnumsByClass(e.getClass());
}

public static <E extends Enum<?>> void iterateOverEnumsByClass(Class<E> c)
{
    for (E o: c.getEnumConstants()) {
        System.out.println(o + " " + o.ordinal());
    }
}

Usage:

enum ABC { A, B, C }
...
iterateOverEnumsByClass(ABC.class);
iterateOverEnumsByInstance(ABC.A);

This is cheap, but should work (at least according to my testing):

public static <T extends Enum<T>> void putItemsInListBox(Class<T> cls, ListBox listbox) {
    for (T item : EnumSet.allOf(cls))
        listbox.addItem(item.toString(), String.valueOf(item.ordinal()));
}

This works because EnumSet has special magical access to non-public members of Enum , which allows it to enumerate the enum's values despite the lack of a values method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM