反射对单例模式(饿汉式)的破坏

import java.lang.reflect.Constructor;

/**
 * @author 苏雪夜酒
 * @version 1.0
 * @date 2022/5/1 13:33
 * 反射:程序运行阶段,获取某一个类的所有属性和方法
 * 所以 反射是对单例模式起到破坏的作用
 * 下面以饿汉式为例,进行演示
 */
public class DestroySingleton {
    public static void main(String [] args){
        /*反射对单例模式的破坏*/
        //1、获取类对象
        Class<Singleton_1> singleton_1Class = Singleton_1.class;
        //2、获取私有的构造方法
        try {
            Constructor<Singleton_1> declaredConstructor = singleton_1Class.getDeclaredConstructor();
            //3、取消Java语言的访问检查 暴力访问
            declaredConstructor.setAccessible(true);
            //4、通过构造 创建对象
            Singleton_1 singleton_1 = declaredConstructor.newInstance();
            Singleton_1 singleton_2 = declaredConstructor.newInstance();
            System.out.println(singleton_1 == singleton_2);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
//饿汉式 单例模式
class Singleton_1{
    //构造方法私有
    private Singleton_1(){
        //防止反射对单例模式的破坏
        if (singleton_1 != null){
            throw new RuntimeException("不允许反射访问。。。");
        }
    };
    //属性私有
    private static Singleton_1 singleton_1 = new Singleton_1();
    //提供对外的访问方法
    public static Singleton_1 getInstance(){
        return singleton_1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值