Wednesday, 14 November 2012

From String to enum in Java

Introduction

In the last year or so I have been making more and more use of the enum support in Java to provide reverse lookup from Strings to obtain a value to use in a switch statement.

Example

When iterating over the child nodes of an XML element with a known set of relevant node names and a corresponding process to perform on the differing child node content.


import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

public enum DwarfNode {
BASHFUL("bashful"), DOC("doc"), DOPEY("dopey"), GRUMPY("grumpy"), HAPPY(
"happy"), SLEEPY("sleepy"), SNEEZY("sneezy");

private String name;

private static final Map lookup
new HashMap();

static {
for (DwarfNode nodeName : EnumSet.allOf(DwarfNode.class)) {
lookup.put(nodeName.name, nodeName);
}
}

public static DwarfNode lookup(String name) {
return lookup.get(name);
}


DwarfNode(String name) {
this.name = name;
}
}


The lookup method takes us from a String to an enum for any recognised name, which can then be used in a switch statement.

When we upgrade to Java 7 - or higher - we will be able to use a String directly in a switch statement, so this approach may become less irrelevant.

No comments:

Post a comment