I have a lot of classes which define some Enum whose values I want loaded from a user-entered String. So I find myself repeating the method:
public final class Status {
public static enum TYPE { Slow, Haste, Sleep, Stop, Stone, Invis, Rage,
Conf, Bleed, Weak, Dumb, Sil, Rot, Lev, Clumsy };
public static Set<Status.TYPE> typesFromString(String string) {
EnumSet<Status.TYPE> set = EnumSet.noneOf(Status.TYPE.class);
if (string == null)
return set;
String[] elements = string.split(",");
for (String element : elements) {
element = element.trim();
for (TYPE type : EnumSet.allOf(Status.TYPE.class)) {
if (type.toString().equalsIgnoreCase(element)) {
set.add(type);
break;
}
}
}
return set;
}
Which is to say, given a string which contains comma-separated elements which match the enum entries, return a set populated with each match.
I'd love to make this generic, so I wouldn't have to maintain ten different copies of it, but I can't quite figure out how to make this generic while returning a set of enums. I think it would look vaguely like the following method:
public static Set<[Enum Class Specified in Argument]> setFromString(String string, [Class of Enum to Work With]) {
Set<E extends Enum<E>> set = EnumSet.noneOf([Class of Enum]);
if (string == null)
return set;
for (String element : string.split(",")) {
element = element.trim().toLowerCase();
for ([Element of Enum] type : EnumSet.allOf([Class of Enum])) {
if (type.toString().trim().toLowerCase().equals(element))
set.add(type);
}
}
}
return set;
SLOW, HASTE, SLEEP, STOP...instead ofSlow, Haste, Sleep, Stop...)set.add(Enum.valueOf(myEnumClazz, element.toUpperCase())), which also avoids the loop. There's prebuilt utilities for getting an enum constant by name.toString()on aStatus.TYPEand display the results as I currently have them typed. If I convert the enum entries to upper-case, I'll get upper-case output.