反射如何破坏单例模式

一个单例类:java

 
public class Singleton {
    private static Singleton instance = new Singleton();   

    private Singleton() {} 

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

经过反射破坏单例模式:多线程

 
public class Test {
    public static void main(String[] args) throws Exception{
        Singleton s1 = Singleton.getInstance();

        Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton s2 = constructor.newInstance();

        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());

    }
}
 

  

671631440
935563443输出结果:

结果代表s1和s2是两个不一样的实例了。函数

经过反射得到单例类的构造函数,因为该构造函数是private的,经过setAccessible(true)指示反射的对象在使用时应该取消 Java 语言访问检查,使得私有的构造函数可以被访问,这样使得单例模式失效。spa

 

若是要抵御这种攻击,要防止构造函数被成功调用两次。须要在构造函数中对实例化次数进行统计,大于一次就抛出异常。.net

 
public class Singleton {
    private static int count = 0;

    private static Singleton instance = null; 

    private Singleton(){
        synchronized (Singleton.class) {
            if(count > 0){
                throw new RuntimeException("建立了两个实例");
            }
            count++;
        }

    }

    public static Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    public static void main(String[] args) throws Exception {

        Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton s1 = constructor.newInstance();
        Singleton s2 = constructor.newInstance();
    }

}
 执行结果:
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.yzz.reflect.Singleton.main(Singleton.java:33)
Caused by: java.lang.RuntimeException: 建立了两个实例
    at com.yzz.reflect.Singleton.<init>(Singleton.java:14)
    ... 5 more
 
在经过反射建立第二个实例时抛出异常,防止实例化多个对象。构造函数中的synchronized是为了防止多线程状况下实例化多个对象。
相关文章
相关标签/搜索