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;
}
}
你能告诉我静态变量是如何序列化的吗??
最佳答案
显然,静态变量可以序列化(但你不应该那样做),因为序列化是保存状态实例的过程em> 一个类,静态变量是所有实例共有的。他们没有说明实例的状态,因此,它根本没有意义。
假设您被允许序列化一个静态变量。然后,当您反序列化该实例时,您将获得该变量的旧副本,此后可能已更改。由于静态变量在类的所有实例之间共享,因此任何实例对变量的更改都必须反射(reflect)在该实例中。
因此,它们不应该被序列化,因为在这些条件下的变量可能违反其作为静态变量的约定。
序列化:-
- 不应序列化静态变量..
反序列化:-
- 实例将获取随类加载的静态字段。因此,可能对该变量所做的任何更改也将对该实例负责。
关于java - 为什么静态变量是序列化的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12775938/