Reputation: 14126
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();
cons.setAccessible(true);
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?
Upvotes: 2
Views: 548
Reputation: 140457
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.
Upvotes: 1