我正在研究单例,我开发了一个非常基本的单例类..
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 ();
}
}
现在下面是我破解单例的一种方法..
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 constructor retrieved is a private one, we need to set its accessibility to true.
pvtConstructor.setAccessible(true);
//Last statement invokes the private constructor and create a new instance of SimpleSingleton class.
SingletonObject notSingleton1 = ( SingletonObject) pvtConstructor.newInstance(null);
System.out.println(notSingleton1.hashCode());
System.out.println("notSingleton1 --->"+notSingleton1.toString());
SingletonObject notSingleton2 = ( SingletonObject) pvtConstructor.newInstance(null);
System.out.println("notSingleton2 --->"+notSingleton2.hashCode());
System.out.println(notSingleton2.toString());
}
}
请告知其他可以破解单例的方法..!!