利用反射机制破坏单例(1)

版权声明:转载请请标明出处。 https://blog.csdn.net/AnIllusion/article/details/81362508

前言

突发奇想,既然单例类通过私有化构造函数来实现单例,而java中通过反射可以获取类中任意的属性和方法,那么可以利用java反射机制获取单例类的私有构造函数来实例化对象,从而获取到新的对象。下面用代码进行实践。

代码实现

单例类 Singleton :

public class Singleton {
    private static Singleton singleton ;

    private Singleton() {
    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                    return singleton;
                }
            }
        }
        return singleton;
    }
}

主函数:

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

public class Main {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //通过调用getSingleton()方式获取对象
        Singleton singleton1 = Singleton.getSingleton();
        //通过反射方式获取对象
        Class singleton1Class = singleton1.getClass();
        Singleton singleton2 = null;
        Constructor<?> constructor = singleton1Class.getDeclaredConstructor();//获取当前Class所表示类中指定的一个的构造器,和访问权限无关
        constructor.setAccessible(true);  //设置私有方法的可访问(切记,这里必须设置,否则会抛出下图的异常)
        singleton2 = (Singleton) constructor.newInstance();//实例化对象
        if(singleton1==singleton2){
            System.out.println("相等");
        }else {
            System.out.println("不相等");
        }
    }
}

输出:

不相等

利用反射机制破坏单例(2)

猜你喜欢

转载自blog.csdn.net/AnIllusion/article/details/81362508
今日推荐