I've found using a static initialization block in an Enum to be great for implementing a custom valueOf function as described here.
public static RandomEnum getEnum(String strVal) {
return strValMap.get(strVal);
}
private static final Map<String, RandomEnum> strValMap;
static {
final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
for(final RandomEnum en : RandomEnum.values()) {
tmpMap.put(en.strVal, en);
}
strValMap = ImmutableMap.copyOf(tmpMap);
}
Now, I have about two dozen of Enum classes and I want to add a custom valueOf for all of them -- is there a way to do that without copy-pasting it into every single type/file?
Make a private static function, and use it multiple times in the initialization block. You could also assign the result of that function to your maps, without the static block at all:
private static <E extends Enum<E>> Map<String,E> makeValueMap(E[] values) {
final Map<String,E> tmpMap = new HashMap<String,E>();
for(final E en : values) {
tmpMap.put(en.name(), en);
}
return tmpMap;
}
Now you can write
private static final Map<String,RandomEnum> strValMap1 = makeValueMap(RandomEnum.values());
private static final Map<String,AnotherEnum> strValMap2 = makeValueMap(AnotherEnum.values());
private static final Map<String,YetAnotherEnum> strValMap3 = makeValueMap(YetAnotherEnum.values());