反射(三)

2020-03-06  本文已影响0人  清沐1412

反射(三)

反射还可能会破坏单例模式,单例模式的特征:

以懒汉模式为例,看一下反射如何破坏单例模式

懒汉单例模式代码:

public class Lazy {

    private static Lazy instance;

    private Lazy(){ }

    public static Lazy getInstance(){
        if (instance==null){
            synchronized (Lazy.class){
                if (instance==null){
                    instance=new Lazy();
                }
            }
        }
        return instance;
    }
}

破坏单例模式:

public class SingletonDestory {
    public static void main(String[] args) {
        Lazy lazyInstance=Lazy.getInstance();
        try {
            Constructor declaredConstructor = Lazy.class.getDeclaredConstructor(null);
            declaredConstructor.setAccessible(true);        //设置私有的构造器,强制访问
            Lazy lazyInstance2= (Lazy) declaredConstructor.newInstance();
            System.out.println(lazyInstance==lazyInstance2);    //嘿嘿,不是一个实例
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
上一篇 下一篇

猜你喜欢

热点阅读