Alex Rivera | Logout

Polymorphically convert Java enum values into a list of strings

Asked 2009-08-11T15:45:15.953
17

I have a handful of helper methods that convert enum values into a list of strings suitable for display by an HTML <select> element. I was wondering if it's possible to refactor these into a single polymorphic method.

This is an example of one of my existing methods:

/**
 * Gets the list of available colours.
 * 
 * @return the list of available colours
 */
public static List<String> getColours() {
  List<String> colours = new ArrayList<String>();

  for (Colour colour : Colour.values()) {
    colours.add(colour.getDisplayValue());  
  }

  return colours;
}

I'm still pretty new to Java generics, so I'm not sure how to pass a generic enum to the method and have that used within the for loop as well.

Note that I know that the enums in question will all have that getDisplayValue method, but unfortunately they don't share a common type that defines it (and I can't introduce one), so I guess that will have to be accessed reflectively...?

Thanks in advance for any help.

Edit
Report

1 Answer

10

You can stick this method in some utility class:

public static <T extends Enum<T>> List<String> getDisplayValues(Class<T> enumClass) {
    try {
        T[] items = enumClass.getEnumConstants();
        Method accessor = enumClass.getMethod("getDisplayValue");

        ArrayList<String> names = new ArrayList<String>(items.length);
        for (T item : items)
            names.add(accessor.invoke(item).toString()));

        return names;
    } catch (NoSuchMethodException ex) {
        // Didn't actually implement getDisplayValue().
    } catch (InvocationTargetException ex) {
        // getDisplayValue() threw an exception.
    }
}

Source: Examining Enums

answered 2009-08-11T16:02:21.830

Your Answer