反射对单例模式的破坏

2020-04-06  本文已影响0人  邵红晓

预防反射攻击的方式是在私有构造函数过程中进行非null判断

        //反射攻击
        Constructor<HungrpSingleton> constructor = HungrpSingleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        HungrpSingleton  s3 = constructor.newInstance();
        HungrpSingleton s4 = HungrpSingleton.getInstance();
        System.out.println(s3==s4);

class HungrpSingleton{
    private static  HungrpSingleton instance = new HungrpSingleton();

    /**
     * 私有化构造函数
     */
    private HungrpSingleton() {
        if (instance!=null){
            throw new RuntimeException("单例不允许多实例");
        }
    }

    public static HungrpSingleton getInstance(){
        return instance;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读