美文网首页
反射破坏单例模式(静态内部类)

反射破坏单例模式(静态内部类)

作者: 天外之石 | 来源:发表于2017-09-01 16:19 被阅读0次

java反射,破坏单例模式

静态内部类

public class Singleton {  
    private static class SingletonHolder {  
        private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}
    public static final Singleton getInstance() {  
        return SingletonHolder.INSTANCE;  
    }  
}

反射实例化单例

public void attackSingleton() {
    Class<?> singletonClass = Singleton.class;
    try {
        Constructor<?>[] constructors = singletonClass.getDeclaredConstructors();
        constructors[0].setAccessible(true);
        Singleton instance1 = (Singleton) constructors[0].newInstance();
        Singleton instance2 = (Singleton) constructors[0].newInstance();
        if (instance1 == instance2) {
            System.out.println("attack failed,攻击Sinleton5失败");
        } else {
            System.out.println("attack success!攻击Sinleton5成功,创建了多个实例");
        }
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

相关文章

网友评论

      本文标题:反射破坏单例模式(静态内部类)

      本文链接:https://www.haomeiwen.com/subject/lqrkjxtx.html