Created
March 13, 2013 12:47
-
-
Save akutz/5151745 to your computer and use it in GitHub Desktop.
A performant way of testing enum membership and parsing an enum from text.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum FuBar | |
{ | |
ONE("one"), | |
TWO("two"); | |
private static final String PATT; | |
private static final Map<String,FuBar> MAP; | |
static | |
{ | |
MAP = new HashMap<String,FuBar>(); | |
StringBuilder sb = new StringBuilder("(?i)"); | |
for (FuBar e : FuBar.values()) | |
{ | |
if (sb.length() > 4) | |
{ | |
sb.append("|"); | |
} | |
sb.append(e); | |
MAP.put(e.toString().toUpperCase(), e); | |
} | |
} | |
private final String value; | |
private FuBar(String value) | |
{ | |
this.value = value; | |
} | |
public boolean isFuBar(String text) | |
{ | |
if (text == null) | |
{ | |
throw new IllegalArgumentException("text is null"); | |
} | |
return text.matches(PATT); | |
} | |
public FuBar parse(String text) | |
{ | |
if (!isFuBar(text)) | |
{ | |
return null; | |
} | |
return MAP[text.toUpperCase()]; | |
} | |
@Override | |
public String toString() | |
{ | |
return this.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment