A privileged cleint can invoke a private constructor reflexively using the AccessibleObject.setAccessible method. If you need to protect this, change the constructor. My question is: how exactly can a private constructor be called? and what is AccessibleObject.setAccessible ??
Obviously, the private constructor can be called by the class itself (for example, from the static factory method). Reflectable, what Bloch says:
import java.lang.reflect.Constructor; public class PrivateInvoker { public static void main(String[] args) throws Exception{
2. What approach do you take with experts in the following groups:
...
As a rule, preference is given to the first. The second (assuming you had to check if TestInstance is null before returning a new instance), gets lazy loading due to the need for synchronization or to be insecure.
I wrote above when your second example did not assign an instance of TestInstance when declaring. As indicated above, the above consideration is not relevant.
Is the second approach more flexible if we have to check a new instance each time or the same instance each time?
This is not about flexibility, but about when the cost of creating one (and only) instance will arise. If you do option a) it takes class loading time. This is usually great, as the class only loads after it is needed.
I wrote above when your second example did not assign an instance of TestInstance when declaring. As indicated now, in both cases, Singleton will be created when the class loads.
What if I try to clone a class / object?
The syntax should not allow cloning for obvious reasons. You need to throw a CloneNotSupportedException and it will be automatically if you for some reason do not implement Cloneable .
a singleton enumeration type is the best way to implement singleton. What for? And How?
Examples for this are given in the book, as well as justifications. Which part do you not understand?