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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With