String对象反序列化踩的坑

直接上问题模拟和总结:

import java.io.*;

public class Main {

    public static void main(String[] args) {

        String a = "abc";
        String b = "abc";
        String c = null;
        System.out.println(a == b);
        a = new String("abc");
        b = new String("abc");
        System.out.println(a == b);

        //将"abc"序列化在字节数组中
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outt = new ObjectOutputStream(byteArrayOutputStream);
            outt.writeObject("abc");
            outt.writeObject("abc");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //从字节数组中反序列化"abc"
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        try {
            ObjectInputStream inn = new ObjectInputStream(byteArrayInputStream);
            b = (String) inn.readObject();
            c = (String) inn.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(a == b);
        System.out.println(a.equals(b));

        a = c;

        System.out.println(a == b);

        //将"abc"序列化在字节数组中
        ByteArrayOutputStream byteArrayOutputStream1 = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outt = new ObjectOutputStream(byteArrayOutputStream1);
            outt.writeObject("abc");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //从字节数组中反序列化"abc"
        ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(byteArrayOutputStream1.toByteArray());
        try {
            ObjectInputStream inn = new ObjectInputStream(byteArrayInputStream1);
            a = (String) inn.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(a == b);

    }
}

结果:


总结:

1、String对象通过""创建时,统一指向方法区中的运行时常量池,所以内容相同时,地址也相同

2、String对象通过new创建(禁止,浪费性能),会先在常量池创建常量,然后在堆中创建对象,两个对象内容相同地址不同,共建三个对象

后面这几条为推测,若有大神,跪求指点:

3、反序列化得的String对象创建在堆里,跟常量池中对象比较时,出现内容相同,地址不同的情况

4、同一个源反序列化得到的具备相同内容的String对象,地址也相同。(求解原因)

5、不同源反序列化得到的具备相同内容的String对象,地址不同。(求解原因)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值