Shirgill Farhan Ansari Shirgill Farhan Ansari - 5 months ago 40
Java Question

When to use a non-instantiable class instead of an enum?

I happen to see the java.util.Collections class. One cannot instantiate this class. I guess it is due to presence of a private Constructor.

The instance could then be created in this way-

Class collections = java.util.Collections.class;
Constructor cons = collections.getDeclaredConstructor();
Collections instance = (Collections) cons.newInstance();

Firstly why didn't the Java API creators stopped this behavior?

It makes be think when should I really prefer a non-instantiable class over an enum?

Answer Source

The short answer to the second question: simply avoid both.

Lengthy answer: actually both options aren't really great. The thing is: you always want to write code that is easy to test.

When you are making static calls; or when you directly call methods on some enum instance, then you simply created code that is hard to test. Because, at some point, you might want to mock things. And in order to mock static/enum calls ... you need Powermock/ito. And those mocking frameworks manipulate your bytecode, and in my eyes, cause much more trouble than they do good.

There is a nice pattern though to use enums as singleton, implementing interfaces, see some older answer of mine here.