私はシングルトンパターンを経験していました.以下は私のシングルトンクラスです..
package CrackingSingleton;
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 ();
}
}
そして、私はそれを壊す方法を試していました。以下は私のコードです...
package CrackingSingleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
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.java").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);
SingletonObject notSingleton2 = ( SingletonObject) pvtConstructor.newInstance(null);
}
}
しかし、上記のクラス CrackingSingleton を実行すると、エラーがスローされます...
Exception in thread "main" java.lang.ClassNotFoundException: CrackingSingleton.SingletonObject.java
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at CrackingSingleton.CrackingSingleton.main(CrackingSingleton.java:14)