反射和反序列化破解单例设计模式java(

(一)通过反射破解

注:其中StrengthSingleDemo02为上一篇发表的单例设计模式的---懒汉式

这里之所以写成这样是因为下一篇将发表怎么防止破解(反射和反序列化)的方法

import java.io.*;
import java.lang.reflect.Constructor;

public class BrokenSingletonDemo {
    public static void main(String[] args)throws Exception {
        // 反射破解懒汉式
        StrengthSingleDemo02 s1 = StrengthSingleDemo02.getInstance();
        StrengthSingleDemo02 s2 = StrengthSingleDemo02.getInstance();
        System.out.println(s1);
        System.out.println(s2);
        // 1.通过反射直接访问私有构造器
        Class<SingletonDemo02> clazz = (Class<SingletonDemo02>)Class.forName("com.ly.Singleton.SingletonDemo02");
        Constructor<SingletonDemo02> c = clazz.getDeclaredConstructor();
        c.setAccessible(true);  // 不加的话IllegalAccessException:非法访问
        SingletonDemo02 s4 = c.newInstance();
        SingletonDemo02 s5 = c.newInstance();
        System.out.println(s4);
        System.out.println(s5);
        /*运行结果
        * com.ly.Singleton.SingletonDemo02@677327b6
          com.ly.Singleton.SingletonDemo02@14ae5a5
         */
    }
}

(二)通过反序列化破解

import java.io.*;
import java.lang.reflect.Constructor;

public class BrokenSingletonDemo {
    public static void main(String[] args)throws Exception {
  
        StrengthSingleDemo02 s1 = StrengthSingleDemo02.getInstance();
        StrengthSingleDemo02 s2 = StrengthSingleDemo02.getInstance();
        System.out.println(s1);
        System.out.println(s2);
 //2.通过序列化和反序列化破解单例

        File file = new File("SingletonBrokenBySerializ.txt");
        try{
            file.createNewFile();
        }catch(Exception e){
            e.printStackTrace();
        }

        // 序列化过程
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(s1);
        oos.close();
        fos.close();
        // 反序列化过程
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        StrengthSingleDemo02 s4 = (StrengthSingleDemo02) ois.readObject();
        System.out.println(s4);
        /*
        * // 运行结果
        * com.ly.Singleton.StrengthSingleDemo02@1540e19d
          com.ly.Singleton.StrengthSingleDemo02@1540e19d
          com.ly.Singleton.StrengthSingleDemo02@58372a00
        * */

    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值