In Java serialization, two member variables cannot be serialized. One is static and one is transient.
But when I wrote a demo, I found that "static member variables can actually get".
The demo code is as follows
Package Com.java;
Import java.io.*;
/** * Created by Huluo on 2016/8/15.
*/public class Hello {public static void main (string[] args) throws IOException, ClassNotFoundException {
User user = new user ();
FileOutputStream FileOutputStream = new FileOutputStream ("Helloworld.txt");
ObjectOutputStream ObjectOutputStream = new ObjectOutputStream (FileOutputStream);
Objectoutputstream.writeobject (user);
FileInputStream FileInputStream = new FileInputStream ("Helloworld.txt");
ObjectInputStream ObjectInputStream = new ObjectInputStream (FileInputStream);
User User1 = (user) objectinputstream.readobject ();
System.out.println (user1);
} class User implements Serializable {String name;
static String password;
transient int age;
Public User () {this.name = "John";
This.password = "password";
This.age = 23;
@Override public String toString () {return name + ' +++++ ' + password + ' +++++ ' + age;
private void WriteObject (ObjectOutputStream out) throws IOException {Out.defaultwriteobject ();
}
}
The idea that static member variables can not be serialized is correct,
The illusion of being able to get a static serialization is because the static belongs to the class and gets the value of the static variable of the class that the JVM has loaded.
When you restart a process or deserialize on another machine, you don't get a static value.
Comment out the following section of my code and rerun it to be validated.
User user = new user ();
// FileOutputStream FileOutputStream = new FileOutputStream ("Helloworld.txt");
// ObjectOutputStream ObjectOutputStream = new ObjectOutputStream (fileoutputstream);
// objectoutputstream.writeobject (user);