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

  • 相关阅读:
    SaltStack 配置SLS过程
    Python 正则表达式
    Python 矩阵的旋转
    SaltStack 远程执行
    SaltStack 配置管理
    SaltStack
    Python 装饰器
    Python 生产者和消费者模型
    Python 迭代器和生成器
    Python json模块
  • 原文地址:https://www.cnblogs.com/ljf-0/p/13875329.html
Copyright © 2011-2022 走看看