Java Foundation - Serializable Serialization Interface

Keywords: Programming Google

Serializable serialization is a means of converting objects into a format that is easy to persist and transfer. It declares that the class is serializable by inheriting an object from the Serializable interface, and then stores and reads objects through ObjectOutputStream and ObjectInputStream stream s, which are briefly described in the comments on the Serializable interface.Here are a few examples to review later.Before presenting an example, declare a class:

public class User implements Serializable {
	//Constructor omission
	private long id;
	private String userName;
	//getter, setter omission
}

serialize

public static void main(String[] args) {
	List<User> userList = new ArrayList<User>();
	userList.add(new User(1, "Zhang San"));
	userList.add(new User(2, "Li Si"));
	try {
		FileOutputStream fileOutputStream = new FileOutputStream("UserSerializeFile");
		ObjectOutputStream objOutputStream = new ObjectOutputStream(fileOutputStream);
		objOutputStream.writeObject(userList);
		objOutputStream.close();
		fileOutputStream.close();
		System.out.println("Serialization complete");
	} catch (IOException e) {
		e.printStackTrace();
	}
}

After execution, you can see the file UserSerializeFile in the project root directory.Because it is saved in binary form, opening it as plain text will display the form of random code.

Deserialize

public static void main(String[] args) {
	try {
		FileInputStream fileInputStream = new FileInputStream("UserSerializeFile");
		ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
		List<User> list = (List<User>)inputStream.readObject();
		for(User user : list) {
			System.out.println("id: " + user.getId() + " userName: " + user.getUserName());
		}
		inputStream.close();
		fileInputStream.close();
	}catch (Exception e) {
		e.printStackTrace();
	}
}

After execution, you can see the following results:

The code is simple, so I won't do any other introduction. This article is mainly to record some relevant knowledge points.

1. What happens when you do not use the Serializable interface?(seems to be a mentally retarded problem)

2. On the class edit page, the IDE prompts "The serializable class User does not declare a static final serialVersionUID field of type long", what is the serialVersionUID mentioned in it?

From the comments on the Serializable interface, you can see that:

The serialization runtime associates a version number with each serializable class, called the serialVersionUID.This version number is used during deserialization to verify that the sender and receiver of the serialized object have loaded serialization-compatible classes for that object.If the recipient has loaded a class for the object that has a different serialVersionUID from the corresponding sender class, deserialization will result in an InvalidClassException error.Serializable classes can explicitly declare their serialVersionUID using a static, final field.

If a serializable class does not explicitly declare a serialVersionUID, the serialization runtime calculates a default serialVersionUID value for the class based on all aspects of the class.However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID calculation is highly sensitive to class details, which may vary depending on the compiler's implementation, and may result in an InvalidClassException during deserialization.It is also recommended that you use the private modifier when declaring a serialVersionUID because the serialVersionUID field does not work as an inherited member.

Please forgive my site English and barely read the introduction with Google Translation.Now that you understand it, you need to verify it yourself to improve your memory.On the basis of the above code to generate a persistent file, I modified the serializable class and added the field phone:

public class User implements Serializable {
	//Constructor omission
	private long id;
	private String userName;
	private String phone;
	//getter, setter omission
}

Executing the deserialization again yields the following results:

You can see that, without displaying the declared serialVersionUID, once the serialized object has been modified, the previously saved file will no longer be readable and parsed.

From the error message, we know the serialVersionUID for the persisted file, so we add the serialVersionUID for the persisted object:

public class User implements Serializable {
	//Constructor omission
	private static final long serialVersionUID = 4164300595038901719L;
	private long id;
	private String userName;
	private String phone;
	//getter, setter omission
}

Deserialization is performed again, and no errors will occur again as allowed by this program.

3. What if some fields do not want to be serialized?

Use the transientkeyword when declaring fields.Whether serialized or deserialized, only transient is added, and the serialization runtime skips processing of this field.

Posted by Vizor on Tue, 21 Apr 2020 10:16:42 -0700