Singleton:如何通过Reflection停止创建实例 [英] Singleton: How to stop create instance via Reflection

查看:119
本文介绍了Singleton:如何通过Reflection停止创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Java中我们可以通过 new clone(),<$创建一个Class实例c $ c>反映和序列化和反序列化

I know in Java we can create an instance of a Class by new, clone(), Reflection and by serializing and de-serializing.

我有创建一个实现Singleton的简单类。

I have create a simple class implementing a Singleton.

我需要一直停止创建我的类的实例。

And I need stop all the way one can create instance of my Class.

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()序列化,但我无法通过Reflection停止它。

In this Class I have managed to stop the class instance by new, clone() and serialization, But am unable to stop it by Reflection.

我创建对象的代码是

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();
}


推荐答案

尝试创建公共构造函数

private Singleton() {
    if( Singleton.singleton != null ) {
        throw new InstantiationError( "Creating of this object is not allowed." );
    }
}

这篇关于Singleton:如何通过Reflection停止创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆