Introduction to Serializable interface

Serializable is a semantic-level interface defined in the java.io package for implementing serialization operations on Java classes. The Serializable interface does not have any methods or fields, but is used to identify Serializable semantics. Classes that implement the Serializable interface can be converted to byte streams by ObjectOutputStream or parsed to objects by ObjectInputStream. For example, we can write a serialized object to a file, then read it from the file again and deserialize it into an object. Simply said is to save the state of various objects in memory, and can be saved to read out the state of the object.

Introduce serialVersionUID

For a JVM, a class to persist must have a tag that allows the JVM to create objects that can be converted to byte data through its IO system for persistence. This tag is the Serializable interface. In the deserialization process, we need to use serialVersionUID to determine which class loads the object, so when we implement the Serializable interface, we will explicitly define the serialVersionUID. During deserialization, if the receiver declares an object of a class whose serialVersionUID is different from the object to be deserialized, the deserialization process causes an InvalidClassException.

View the source code

package java.io;
public interface Serializable {

}
Copy the code

The test code

The Person class

import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 8241970228716425282L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [name=" + name + "]"; }}Copy the code

The test class

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Test { public static void main(String[] args) { Person p = new Person(); p.setName("feige"); writeObj(p); Person p2 = readObj(); System.out.println(p2); } // serialize public static void writeObj(Person p) {try {ObjectOutputStream ObjectOutputStream = new ObjectOutputStream(new FileOutputStream("E://1.txt")); objectOutputStream.writeObject(p); objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); Public static Person readObj() {Person p = null; try { ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("E://1.txt")); try { p = (Person)objectInputStream.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } return p; }}Copy the code

Console output: Person [name=feige]