为什么静态变量是序列化的?

Gir*_*air 7 java serialization static-members

public class MySerializable implements Serializable{

    private int x=10;
    private static int y = 15;
    public static void main(String...args){
        AnotherClass a = new AnotherClass();
        AnotherClass b;
        //Serialize
        try {
            FileOutputStream fout = new FileOutputStream("MyFile.ser");
            ObjectOutputStream Oout = new ObjectOutputStream(fout);
            Oout.writeObject(a);
            System.out.println( a.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //De-serialize
        try {
            FileInputStream fis = new FileInputStream("MyFile.ser");
            ObjectInputStream  Oin = new ObjectInputStream (fis); 
            b = (AnotherClass) Oin.readObject();
            System.out.println( b.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }

    }
}

class AnotherClass  implements Serializable{  

    transient int x = 8;  
    static int y = 9;  

    @Override  
    public String toString() {  
        return "x : " + x + ", y :" + y;  
    }  
}
Run Code Online (Sandbox Code Playgroud)

你能告诉我静态变量是如何序列化的吗?

Roh*_*ain 11

显然,静态变量可以被串行化(但你不应该这样做),因为序列化是的过程中保存状态的的实例类的,和静态变量是共同的所有实例.他们没有说实例的状态,所以根本就没有意义.

假设您被允许序列化一个静态变量.然后,当您反序列化实例时,您将获得该变量的旧副本,此变量可能从那时起已更改.由于静态变量在类的所有实例之间共享,因此必须在此实例中反映来自任何实例的变量的更改.

因此,它们不应该被序列化,因为在这些条件下的变量可能会违反其作为静态变量的契约.

序列化: -

  • 不应该序列化静态变量..

反序列化: -

  • 实例将获取随类加载的静态字段.因此,对该变量可能进行的任何更改也将对此实例负责.