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",因为没有改变静态变量的值。

  • 相关阅读:
    Mybatis中的设计模式
    Mybatis的#{}和${}的区别是什么?
    ES的写入速度优化
    康师傅JVM:垃圾回收相关概念(十六)
    i++为什么不是原子操作?
    Zookeeper的watch机制
    LeetCode 1.两数之和
    ESP 8266 引脚图
    Arduino 将 String 转化为 int
    微擎修改 icon.jpg 后项目主页未变
  • 原文地址:https://www.cnblogs.com/ljf-0/p/13875329.html
Copyright © 2011-2022 走看看