例如,我有Singleton静态字段的类instance:
public class Singleton {
private static Singleton instance;
// other code, construct, getters, no matter
}
Run Code Online (Sandbox Code Playgroud)
我可以用两个不同的类加载器加载这个类两次.我怎么能避免它?这是不安全和危险的.
另外,如果我将实例设置为null,它是否会为两个类设置为null?
Singleton singleton = Singleton.getInstance();
singleton = null;
Run Code Online (Sandbox Code Playgroud) 我正在研究单身人士,我开发了一个非常基本的单身人士课程.
public class SingletonObject {
private static SingletonObject ref;
private SingletonObject () //private constructor
{ }
public static synchronized SingletonObject getSingletonObject()
{
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException
{throw new CloneNotSupportedException ();
}
}
Run Code Online (Sandbox Code Playgroud)
现在下面是我破解单身人士的一种方式..
public class CrackingSingleton {
public static void main(String[] args) throws ClassNotFoundException,
IllegalArgumentException, SecurityException,
InstantiationException, IllegalAccessException,
InvocationTargetException {
//First statement retrieves the Constructor object for private constructor of SimpleSingleton class.
Constructor pvtConstructor = Class.forName("CrackingSingleton.SingletonObject").getDeclaredConstructors()[0];
//Since the …Run Code Online (Sandbox Code Playgroud)