这个问题,和我之前的问题一样,参考了Effective Java。这次我有很多子问题。
A privileged client can invoke the private constructor reflectively with the aid of the
AccessibleObject.setAccessible()
method. If you need to defend against this, modify the constructor.
How, exactly, can a private constructor be invoked? And what isAccessibleObject.setAccessible()
?What approach do you experts follow with singletons?
// Approach A public class Test{ public static final Test TestInstance = new Test(); private Test(){ ... } . . . } // Approach B public class Test{ private static final Test TestInstance = new Test(); private Test(){ ... } public static Test getInstance() { return TestInstance; } . . . }
Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?
What if I try to clone the class/object?
a single-element enum type is the best way to implement a singleton.
Why? How?