单例:如何通过反射停止创建实例
2022-09-01 00:48:17
我知道在 Java 中,我们可以通过 、 和 . 创建类的实例。new
clone()
Reflection
serializing and de-serializing
我创建了一个实现单例的简单类。
我需要停止一直可以创建我的类的实例。
public class Singleton implements Serializable{
private static final long serialVersionUID = 3119105548371608200L;
private static final Singleton singleton = new Singleton();
private Singleton() { }
public static Singleton getInstance(){
return singleton;
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cloning of this class is not allowed");
}
protected Object readResolve() {
return singleton;
}
//-----> This is my implementation to stop it but Its not working. :(
public Object newInstance() throws InstantiationException {
throw new InstantiationError( "Creating of this object is not allowed." );
}
}
在这个类中,我设法通过 和 停止类实例,但无法通过反射停止它。new
clone()
serialization
用于创建对象的我的代码是
try {
Class<Singleton> singletonClass = (Class<Singleton>) Class.forName("test.singleton.Singleton");
Singleton singletonReflection = singletonClass.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}