Annotations for Java enum singleton

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.

+8
java enums singleton annotations
source share
2 answers

I do not know such an annotation in public java libraries, but you can define a compilation-time annotation that will be used for your projects. Of course, you need to write an annotation handler and call APT somehow (with ant or maven ) to check your declared @EnumSingleton abbreviations at compile time for the intended structure.

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

+2
source share

You can use something like this -

 public class SingletonClass { private SingletonClass() { // block external instantiation } public static enum SingletonFactory { INSTANCE { public SingletonClass getInstance() { return instance; } }; private static SingletonClass instance = new SingletonClass(); private SingletonFactory() { } public abstract SingletonClass getInstance(); } } 

And you can access in some other class like -

 SingletonClass.SingletonFactory.INSTANCE.getInstance(); 
+3
source share

All Articles