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;
}
}
¿Puede decirme cómo se serializa la variable estática?¿Cómo es que la variable estática está serializada?
Esta respuesta no es correcta, la variable estática no está siendo almacenado y restaurado por la serialización. Las variables estáticas no pueden ni están serializadas; el valor del campo estático permanece en el campo de clase todo el tiempo ... nunca dejó la memoria en absoluto. –