I have an Enum class that requires a function object (in this case, one of Guava's StringConverters) to initialize one of the fields. It could look like this:
private MyEnum(String input) {
this.myField = someFunctionObject.convert(input);
}
However, once all the members of the enum are finished loading, I have no use for this object. What's the best practice for handling this? It seems my options are:
- Have a private static object somewhere that persists after the enum is finished initializing, creating a pseudo-memory leak. (I could also
null
it out when I'm done, but then I still have a useless static reference which still is ugly.) - Create and re-create the object each time the enum constructor is called.
- Make the field non-
final
and use a static initializer block that only needs to create the function object once, then loops over the enums and initializes the fields outside of the constructor.
It's not like this is a big deal, but this process has come up a few times, and I don't like any of these solutions. I don't think this is an issue of premature micro-optimization, either, it's an issue of the most elegant/ readable/ sensible way to perform this.