Annotations for Java enum singleton

annotations, enums, java, singleton

Solution

I'm not aware of such an annotation in public java libraries, but you can define yourself such a compile time annotation to be used for your projects. Of course, you need to write an annotation processor for it and invoke somehow APT (with ant or maven) to check your `@EnumSingleton` annoted enums at compile time for the intended structure.

Here is a resource on how to write and use compile time annotations.

Problem

As Bloch states in Item 3 ("Enforce the singleton property with a private constructor or an enum type") of Effective Java 2nd Edition, a single-element enum type is the best way to implement a singleton. Unfortunately the old private constructor pattern is still very widespread and entrenched, to the point that many developers don't understand what I'm doing when I create enum singletons. A simple `// Enum Singleton` comment above the class declaration helps, but it still leaves open the possibility that another programmer could come along later and add a second constant to the enum, breaking the singleton property. For all the problems that the private constructor approach has, in my opinion it is somewhat more self-documenting than an enum singleton. I think what I need is an annotation which both states that the enum type is a singleton and ensures at compile-time that only one constant is ever added to the enum. Something like this: ``` @EnumSingleton // Annotation complains if > 1 enum element on EnumSingleton public enum EnumSingleton { INSTANCE; } ``` Has anyone run across such an annotation for standard Java in public libraries anywhere? Or is what I'm asking for impossible under Java's current annotation system? UPDATE One workaround I'm using, at least until I decide to actually bother with rolling my own annotations, is to put `@SuppressWarnings("UnusedDeclaration")` directly in front of the `INSTANCE` field. It does a decent job of making the code look distinct from a straightforward enum type.

Original source