首页 > 其他 > 详细

反射(三)

时间:2020-03-05 22:25:57      阅读:63      评论:0      收藏:0      [点我收藏+]

反射(三)

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

  • 私有化构造方法
  • 提供全局唯一的公有访问点

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

懒汉单例模式代码:

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

    }
}

反射(三)

原文:https://www.cnblogs.com/qingmu1412/p/12423200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!