I have a singleton like this.
public class BookingFactory {
private final static BookingFactory instance;
static {
instance = new BookingFactor
Adapted from Making the Java Singleton Reflection Proof when using Lazy Loading:
package server;
import java.lang.reflect.ReflectPermission;
import java.security.*;
public class JavaSingleton {
private static JavaSingleton INSTANCE = null;
private JavaSingleton() {
ReflectPermission perm = new ReflectPermission("suppressAccessChecks", "");
AccessController.checkPermission(perm);
}
synchronized public static final JavaSingleton getInstance() {
if (INSTANCE == null) {
AccessController.doPrivileged(new PrivilegedAction
The constructor has a check to see if the caller has access to it. As the link explains, a policy file that permits the Singleton class itself to call the constructor will need to be created.
Bohemian's method of throwing an exception does not prevent a client from reflectively calling the constructor before getInstance() is called. Even though it ensures that only one instance gets created, there's no guarantee that this is done by the Singleton class' getInstance()
method.
The access control check will prevent this unwanted instantiation.