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.
We can convert an enum to string by calling the ToString() method of an Enum.
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.
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.
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.
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