反射破坏单例模式以及如何防御

推荐:Java设计模式汇总

反射破坏单例模式以及如何防御

需要了解实现单例模式的各种方法,可以参考下方这篇博客。
设计模式-单例模式(Singleton Pattern)

单例模式类Singleton,是使用静态内部类实现的单例模式。

package com.kaven.design.pattern.creational.singleton;

public class Singleton{
    private Singleton(){}

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

    private static class Inner{
        private static final Singleton instance = new Singleton();
    }
}

接下来,使用反射来破坏单例模式。

package com.kaven.design.pattern.creational.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectionDestroyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class objectClass = Singleton.class;
        Constructor constructor = objectClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton instance = Singleton.getInstance();
        Singleton newInstance = (Singleton) constructor.newInstance();

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

因为在单例模式中的构造器是私有的,在Singleton类外部是不能随便调用的,但是通过反射就不一定了,通过这段代码constructor.setAccessible(true)便可以得到构造器的访问权。

结果:

com.kaven.design.pattern.creational.singleton.Singleton@4554617c
com.kaven.design.pattern.creational.singleton.Singleton@74a14482
false

很明显,反射确实破坏了单例模式。

我们如何应对呢?
即便是通过反射来创建实例,也是调用类中的构造器来实现的,所以我们可以在构造器中做文章。
改造Singleton类中的私有构造器如下:

package com.kaven.design.pattern.creational.singleton;

public class Singleton{
    private Singleton(){
        if(Inner.instance != null){
            throw new RuntimeException("单例模式禁止反射创建实例!");
        }
    }

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

    private static class Inner{
        private static final Singleton instance = new Singleton();
    }
}

结果:

Exception in thread "main" java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.kaven.design.pattern.creational.singleton.ReflectionDestroyTest.main(ReflectionDestroyTest.java:12)
Caused by: java.lang.RuntimeException: 单例模式禁止反射创建实例!
	at com.kaven.design.pattern.creational.singleton.Singleton.<init>(Singleton.java:6)
	... 5 more

很显然报异常了,这样便防止了这种方法实现的单例模式被反射破坏。

饿汉式实现的单例模式都可以这样来防止单例模式被反射破坏。
懒汉式实现的单例模式是不可以防止被反射破坏的。
双重检查锁式实现的单例模式来进行测试,其他的懒汉式实现的单例模式同理。

package com.kaven.design.pattern.creational.singleton;

public class Singleton {
    private static volatile Singleton instance ;

    private Singleton(){
        if(instance != null){
            throw new RuntimeException("单例模式禁止反射创建实例!");
        }
    }

    public static Singleton getInstance(){

        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

上面的测试方法是没有问题的。
我们改一改测试方法:

package com.kaven.design.pattern.creational.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectionDestroyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class objectClass = Singleton.class;
        Constructor constructor = objectClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        
        Singleton newInstance = (Singleton) constructor.newInstance();
        Singleton instance = Singleton.getInstance();

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

很明显,我们把通过反射创建实例和调用静态方法getInstance()获得实例的位置互换了,所以一开始通过反射创建实例调用构造器,此时构造器中的判断instance != null是无用的,所以这种方法是不适用懒汉式实现的单例模式来防止被反射破坏的。
结果也很明显:

com.kaven.design.pattern.creational.singleton.Singleton@4554617c
com.kaven.design.pattern.creational.singleton.Singleton@74a14482
false

我们可以使用信号量吗?
代码如下:

package com.kaven.design.pattern.creational.singleton;

public class Singleton {
    private static volatile Singleton instance ;
    private static boolean flag = true;

    private Singleton(){
        if(flag){
            flag = false;
        }
        else{
            throw new RuntimeException("单例模式禁止反射创建实例!");
        }
    }

    public static Singleton getInstance(){

        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

这样我们是不是只能调用一次构造器了,所以也就可以防止反射了?
反射可以获得私有构造器的访问权,难道就不能获得私有静态变量的访问权吗?
很显然是可以的,所以这种方法也是行不通的。
如果定义信号量为final呢?就更不行了吧,因为都不能更改。
测试:

package com.kaven.design.pattern.creational.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectionDestroyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Class objectClass = Singleton.class;
        Constructor constructor = objectClass.getDeclaredConstructor();
        constructor.setAccessible(true);

        Singleton instance = Singleton.getInstance();

        Field flag = objectClass.getDeclaredField("flag");
        flag.setAccessible(true);
        flag.set(instance , true);
        Singleton newInstance = (Singleton) constructor.newInstance();

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

结果:

com.kaven.design.pattern.creational.singleton.Singleton@1540e19d
com.kaven.design.pattern.creational.singleton.Singleton@677327b6
false

很显然出问题了。
所以懒汉式实现的单例模式是不可以防止被反射破坏的。

评论中的例子
例一:

private Singleton() {
        // 防止反射对单例的破坏
        if(instance!=null){	// 单例已有实例
            throw new RuntimeException("禁止使用反射创建单例");
        }
        instance = this;
}

测试:

package com.kaven.system;

import lombok.SneakyThrows;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Singleton {
    private static volatile Singleton instance ;

    private Singleton() throws InterruptedException {
        // 防止反射对单例的破坏
        if(instance!=null){	// 单例已有实例
            throw new RuntimeException("禁止使用反射创建单例");
        }
        // 如果执行到这里,需要等待一段时间才能继续执行,比如时间片用完了
        Thread.sleep(100);
        instance = this;
        System.out.println(this + " " + Thread.currentThread().getName());
    }

    public static Singleton getInstance() throws InterruptedException {

        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException, InterruptedException {
        Class objectClass = Singleton.class;
        Constructor constructor = objectClass.getDeclaredConstructor();
        constructor.setAccessible(true);

        Thread thread = new Thread(new Singleton.myRunnable());
        thread.setName("kaven");
        thread.start();
        constructor.newInstance();
    }

    static class myRunnable implements Runnable{

        @SneakyThrows
        @Override
        public void run() {
            Singleton.getInstance();
        }
    }
}

结果:
在这里插入图片描述
还是可以破坏单例模式的,因为我们不知道时间片什么时候用完,或者在执行过程中遇到什么问题。

例二:

    private Singleton(){
        synchronized (Singleton.class) {
            // 防止反射对单例的破坏
            if (instance != null) {    // 单例已有实例
                throw new RuntimeException("禁止使用反射创建单例");
            }
            instance = this;
        }
    }

测试:

package com.kaven.system;

import lombok.SneakyThrows;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Singleton {
    private static volatile Singleton instance ;
    private static boolean throwException = true;

    private Singleton(){
        synchronized (Singleton.class) {
            // 防止反射对单例的破坏
            if (instance != null) {    // 单例已有实例
                throw new RuntimeException("禁止使用反射创建单例");
            }
            System.out.println(this + " " + Thread.currentThread().getName());
            // 如果出现异常,异常结束时会释放掉锁
            if(Singleton.throwException) throw new RuntimeException();
            instance = this;
        }
    }

    public static Singleton getInstance(){

        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
        Class objectClass = Singleton.class;
        Constructor constructor = objectClass.getDeclaredConstructor();
        constructor.setAccessible(true);

        Thread thread = new Thread(new Singleton.myRunnable());
        thread.setName("kaven");
        thread.start();

        Singleton singleton = null;
        try {
            singleton = (Singleton) constructor.newInstance();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            // 虽然还是null
            System.out.println(singleton);
        }
    }

    static class myRunnable implements Runnable{

        @SneakyThrows
        @Override
        public void run() {
            Thread.sleep(50);
            Singleton.throwException = false;
            Singleton singleton = Singleton.getInstance();
            System.out.println(singleton);
        }
    }
}

结果:
在这里插入图片描述
虽然打印出来了两个实例,但只有一个实例可用,这种情况是否符合单例模式呢?大家可以相互讨论一下。

如果有说错的地方,请大家不吝赐教(记得留言哦~~~~)。

扩展阅读:
为什么要用枚举实现单例模式(避免反射、序列化问题)
序列化破坏单例模式以及如何防御的应用与Debug分析
Java高级特性—反射

  • 10
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITKaven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值