当前位置 > it书童 > java > 正文

单例模式如何应对反射攻击

java it书童 2020-12-26 22:25:02 0赞 0踩 100阅读 0评论
public class HungrySingleton implements Serializable {
    private final static HungrySingleton hungrySingleton = new HungrySingleton();
    private HungrySingleton() {
    }

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }

    private Object readResolve() {
        return hungrySingleton;
    }
}
public class Test {
    public static void main(String[] args) throws Exception {
        Class<HungrySingleton> objectClass = HungrySingleton.class;
        Constructor<HungrySingleton> constructor = objectClass.getDeclaredConstructor();
        // 通过反射,将权限打开
        constructor.setAccessible(true);
        HungrySingleton instance = HungrySingleton.getInstance();
        HungrySingleton newInstance = constructor.newInstance();

        System.out.println(instance);
        System.out.println(newInstance);
        System.out.println(instance == newInstance);
    }
}

结果:

design.pattern.creational.singleton.HungrySingleton@610455d6
design.pattern.creational.singleton.HungrySingleton@511d50c0
false

对于饿汉式单例模式的防御

private HungrySingleton() {
    if (hungrySingleton != null) {
        throw new RuntimeException("单例构造器禁止反射调用");
    }
}

这种防御方式仅对于类加载时就生成实例的单例模式有效

对于懒汉式单例模式是不起作用的,哪怕使用了再复杂的逻辑,反射也能直接暴力修改程序预设的判断,就是这么粗暴与牛逼,完全不讲武德

具体原理可通过断点调试得知

关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
转载须注明出处:https://www.itshutong.com/articles/1013