As Bloch says in element 3 ("Enforce the use of a singleton property with a private constructor or enumeration type") Effective Java 2nd Edition, an enumeration type with one element is the best way to implement singleton . Unfortunately, the old private constructor template is still very common and rooted to such an extent that many developers do not understand what I do when I create single enumeration lists.
A simple // Enum Singleton comment above the class declaration helps, but it still leaves open the possibility that another programmer may come later and add a second constant to the enumeration, violating the singleton property. For all the problems that the private constructor approach has, in my opinion, it is somewhat more self-documented than renaming a singleton.
I think I need an annotation that says that an enum type is singleton and ensures at compile time that only one constant is ever added to an enum. Something like that:
@EnumSingleton // Annotation complains if > 1 enum element on EnumSingleton public enum EnumSingleton { INSTANCE; }
Does anyone come across such annotation for standard Java in public libraries anywhere? Or is this what I ask for the impossibility in the current annotation of the Java system?
UPDATE
One workaround that I use, at least until I dare to actually work hard by folding my own annotations, is to put @SuppressWarnings("UnusedDeclaration") immediately before the INSTANCE field. This does a decent job of creating code that is different from a simple enumeration type.
java enums singleton annotations
Andrew Bissell
source share