如果我在同一文件中序列化和反序列化对象,为什么静态成员会被序列化

问题描述 投票:0回答:1

如果我在同一个文件中序列化和反序列化一个对象,我不明白为什么静态成员也会被序列化,但是如果我评论序列化部分,它工作得很好,如果在类中完成,与它们有什么关系吗? 根据文档,静态成员无法序列化,但打印时的静态成员显示序列化值。

import java.io.*;

class Student_serial implements Serializable
{
    int rollNo;
    String name;
    String dept;
    float avg;

    public static int Data = 10;
    public transient int t = 100;

    public Student_serial()
    {

    }

    public Student_serial(int r, String n, String d, float a)
    {
        rollNo = r;
        name = n;
        dept = d;
        avg = a;

        Data = 500;
        t = 500;
    }

    public String toString()
    {
        return "\nStudent Details\n"+
                "\nRoll "+rollNo+
                "\nName "+name+
                "\nAverage "+avg+
                "\nDept "+dept+
                "\nData "+Data+
                "\nTransient "+t+"\n";
    }
}

public class Object_Stream_And_Serialisation {
    public static void main(String[] args)  throws Exception
    {

        //Serialisation of Object
        FileOutputStream fos = new FileOutputStream("C:/users/kbb91/Desktop/A-B-Java/Studetn3.txt");

        ObjectOutputStream oos = new ObjectOutputStream(fos);

        Student_serial s = new Student_serial(7, "KB", "Army", 9.5f);

        oos.writeObject(s);

        //Deserialization of Object
        FileInputStream fis = new FileInputStream("C:/users/kbb91/Desktop/A-B-Java/Studetn3.txt");

        ObjectInputStream ois = new ObjectInputStream(fis);

        Student_serial s1;

        s1 = (Student_serial) ois.readObject();

        System.out.println(s1);


    }

}

我得到的输出

Student Details

Roll 7
Name KB
Average 9.5
Dept Army
Data 500
Transient 0

我期望的输出

Student Details

Roll 7
Name KB
Average 9.5
Dept Army
Data 10
Transient 0
java serialization
1个回答
0
投票

根据文档......实际上......

static
字段不会通过Java对象序列化进行序列化和反序列化。

这里实际发生的是

static int Data
字段被第二个
10
构造函数设置为
Student_serial

© www.soinside.com 2019 - 2024. All rights reserved.