Tuesday, October 5, 2010

Customized ValueOf

When I am writing enum I very often found myself implementing static method similar to standard enum’s valueOf() but based on field other than name:

public static TestOne valueOfDescription(String description) {
    for (TestOne v : values()) {
        if (v.description.equals(description)) {
            return v;
    throw new IllegalArgumentException(
    "No enum const " + TestOne.class + "@description." + description);
where “description” is yet another String field in my enum. And I am not alone. See for example this beautiful article.
Obviously this method is very ineffective. Every time it is invoked it iterates over all members of enum. Here is the improved version that uses cache:

 private static Map map = null;
 public static TestTwo valueOfDescription(String description) {
  synchronized(TestTwo.class) {
   if (map == null) {
    map = new HashMap();
    for (TestTwo v : values()) {
     map.put(v.description, v);

  TestTwo result = map.get(description);
  if (result == null) {
         throw new IllegalArgumentException(
                 "No enum const " + TestTwo.class + "@description." + description);

  return result;
It is fine if we have only one enum and only one custom field that we use to find the enum value. But if number each one of 20 enums has 3 such fields the code will be very verbose. As far as I dislike copy/paste programming I have implemented utility that helps to create such methods. I called this utility class ValueOf. It has 2 public methods:

public static <T extends Enum<T>, V> T valueOf(Class<T> enumType, String fieldName, V value);
that finds required field in specified enum. It is implemented utilizing reflection and uses hash table initialized during the first call for better performance. Other overridden valueOf() looks like:

public static <T extends Enum<T>> T valueOf(Class<T> enumType, Comparable<T> comparable);
This method does not cache results, so it iterates over enum members on each invocation. But it is more universal: you can implement comparable as you want, so this method may find enum member using more complicated criteria.
Full code with examples and JUnit test case is available here.


Java Enums provide ability to locate enum member by name. This article describes utility that makes it easy to locate enum members by any other field.

1 comment: