zoukankan      html  css  js  c++  java
  • java static序列化

    https://blog.csdn.net/yangxiangyuibm/article/details/43227457

    博主讲的很好

    package test;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
     
    public class Main{
        
        public static void main(String[] args){
            
            Person person = new Person();
            person.setAge(25);
            person.setName("YXY");
            Person.test="JAVA"; //modify the test value
            
            File file = new File("c:/test.txt");
            try {
                OutputStream out = new FileOutputStream(file);
                ObjectOutputStream objout = new ObjectOutputStream(out);
                objout.writeObject(person);
                objout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            //code segment 1
            Person perobj = null;
            try {
                InputStream in = new FileInputStream(file);
                ObjectInputStream objin = new ObjectInputStream(in);
                perobj = (Person)objin.readObject();
                System.out.println(perobj.test);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    正是因为static变量不会被序列化,所以输出perobj.test时,因为perobj是一个Person类型的变量,所以jvm会到方法区中(jdk1.8之后应该到堆中找到静态变量)

    发现Person类型静态属性是“JAVA”,所以打印出"JAVA"

    package test;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
     
    public class TEST {
        public static void main(String[] args){
            File file = new File("c:/test.txt");
            
            //code segment 1
            Person perobj = null;
            try {
                InputStream in = new FileInputStream(file);
                ObjectInputStream objin = new ObjectInputStream(in);
                perobj = (Person)objin.readObject();
                System.out.println(perobj.test);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    这时输出的就是"IBM",因为没有改变静态变量的值。

  • 相关阅读:
    (五)SpringCloud学习系列-构建部门微服务消费者Module
    (四)SpringCloud学习系列-构建部门微服务提供者Module
    (三)SpringCloud学习系列-Rest微服务构建
    git提交 显示作者名不是自己
    linux一些常见命令
    支付宝退款demo
    ffmpeg截取视频
    excel导入数据到mysql
    二分法与冒泡排序
    mysql的级联删除
  • 原文地址:https://www.cnblogs.com/ljf-0/p/13875329.html
Copyright © 2011-2022 走看看