Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphically convert Java enum values into a list of strings

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.

like image 928
John Topley Avatar asked Aug 11 '09 15:08

John Topley


People also ask

Can enum be converted to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Can enum be converted to string Java?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can we create list of enum in Java?

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum.


1 Answers

using Class#getEnumConstants() is simple:

static <T extends Enum<T>> List<String> toStringList(Class<T> clz) {
     try {
        List<String> res = new LinkedList<String>();
        Method getDisplayValue = clz.getMethod("getDisplayValue");

        for (Object e : clz.getEnumConstants()) {
            res.add((String) getDisplayValue.invoke(e));

        }

        return res;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

this is not completely typesafe since you can have an Enum without a getDisplayValue method.

like image 165
dfa Avatar answered Oct 05 '22 07:10

dfa