Java
provides a valueOf()
method for every Enum
object, so given an enum
like
public enum Day {
and it would implement exactly the functionality of the Day.lookup() method for any enum, without the need to re-write the same method for each enum.
Probably you can write a utility class for doing that as the following.
public class EnumUtil {
private EnumUtil(){
//A utility class
}
public static > T lookup(Class enumType,
String name) {
for (T enumn : enumType.getEnumConstants()) {
if (enumn.name().equalsIgnoreCase(name)) {
return enumn;
}
}
return null;
}
// Just for testing
public static void main(String[] args) {
System.out.println(EnumUtil.lookup(Day.class, "friday"));
System.out.println(EnumUtil.lookup(Day.class, "FrIdAy"));
}
}
enum Day {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
It would have been nice if there was a way in Java for us to extend the Enum class by implicitly adding methods just the way values() method is added but I don't think there is a way to do that.