2

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?

Community
  • 1
  • 1
naumcho
  • 18,671
  • 14
  • 48
  • 59

2 Answers2

1

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());

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

To implement the same mechanism WITHIN the enum classes, I guess no, because an enum cannot inherit from a class (only interfaces), hence has no way to share implementations.

You can, however, implement a standalone utility that does this for all the different enum types together. The utility will look up enum values by enum type + strVal.

James
  • 537
  • 3
  • 11