Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Enum Tricks: Customized valueOf

DZone's Guide to

Enum Tricks: Customized valueOf

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

When I am writing enumerations I very often found myself implementing a static method similar to the standard enum’s valueOf() but based on field rather 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 this article for example. Obviously this method is very ineffective. Every time it is invoked it iterates over all members of the enum. Here is the improved version that uses a 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 we have 20 enums, and each has 3 such fields, then the code will be very verbose. As I dislike copy/paste programming I have implemented a 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);

which finds the required field in specified enum. It is implemented utilizing reflection and uses a hash table initialized during the first call for better performance. The 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 members using more complicated criteria.

Full code with examples and JUnit test case are available here.

Conclusions

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

Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.

Topics:
java ,tips ,enum

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}