Update:
In java 8, this is one line for an arbitrary enum class using a stream:
public static String[] getNames(Class<? extends Enum<?>> e) { return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new); }
In java 7, a little less elegant, but this one-liner trick does the trick:
public static String[] names() { return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", "); }
In addition, here is a version of this that will work for any listing:
public static String[] getNames(Class<? extends Enum<?>> e) { return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", "); }
What would you call so:
String[] names = getNames(State.class); // any other enum class will work too
Bohemian Dec 09 '12 at 1:18 2012-12-09 01:18
source share