Five things you don't know about Java object serialization (1)
A few years ago, when I was writing an application in Java with a software team, I realized the benefits of having a little more knowledge about Java object serialization than the average programmer.
About this series
Do you think you understand Java programming? As a matter of fact, most programmers only learn enough knowledge to complete the tasks at hand for the Java platform. In this series, Ted Neward goes deep into the core functions of the Java platform and reveals some little-known facts to help you solve the toughest programming challenges.
About a year ago, a developer responsible for managing all user settings of the application decided to store the user settings inHashtableAnd thenHashtableSerialized to the disk for persistence. When the user changes the settingsHashtableWrite to disk.
This is an elegant and open setup system, but when the team decidesHashtableMigrate to Java Collections LibraryHashMapThe system is facing a crash.
HashtableAndHashMapThe format on the disk is different and incompatible. Unless you set up to run a type of data conversion utility for each persistent user), you can only keep usingHashtableAs the storage format of the application.
The team felt deadlocked, but it was only because they were not aware of an important fact about Java serialization: Java serialization allowed to change the type over time. After I showed them how to automatically replace serialization, they finally finishedHashMap.
This is the first article in this series. This series specifically reveals some useful little knowledge about the Java platform-this little knowledge is hard to understand, but it will be useful sooner or later to solve the Java programming challenge.
Java object serialization API is a good choice at the beginning, because it exists in JDK 1.1 from the very beginning. Five Things About serialization described in this article will persuade you to review those standard Java APIs.
About this series
Java object serialization is one of the pioneering features introduced in JDK 1.1. It is used as a mechanism to convert the status of Java objects into byte Arrays for storage or transmission. Later, you can still convert the byte array back to the original state of the Java object.
In fact, the idea of serialization is to "freeze" the object state, write the object state to the disk, transfer it through the network, etc.), then "unfreeze" the state, and obtain available Java objects again. All these things happen like magic, thanksObjectInputStream/ObjectOutputStreamClass, fully fidelity metadata, and the willingness of programmers to useSerializableMark their classes to "Participate" in the process.
Listing 1 shows an implementationSerializableOfPersonClass.
Listing 1. Serializable Person
package com.tedneward;public class Person implements java.io.Serializable{ public Person(String fn, String ln, int a) { this.firstName = fn; this.lastName = ln; this.age = a; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public Person getSpouse() { return spouse; } public void setFirstName(String value) { firstName = value; } public void setLastName(String value) { lastName = value; } public void setAge(int value) { age = value; } public void setSpouse(Person value) { spouse = value; } public String toString() { return "[Person: firstName=" + firstName + " lastName=" + lastName + " age=" + age + " spouse=" + spouse.getFirstName() + "]"; } private String firstName; private String lastName; private int age; private Person spouse;}
SetPersonAfter serialization, it is easy to write the object state to the disk and read it again. The following JUnit 4 unit test demonstrates this.
Listing 2. deserializing Person
public class SerTest{ @Test public void serializeToDisk() { try { com.tedneward.Person ted = new com.tedneward.Person("Ted", "Neward", 39); com.tedneward.Person charl = new com.tedneward.Person("Charlotte", "Neward", 38); ted.setSpouse(charl); charl.setSpouse(ted); FileOutputStream fos = new FileOutputStream("tempdata.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ted); oos.close(); } catch (Exception ex) { fail("Exception thrown during test: " + ex.toString()); } try { FileInputStream fis = new FileInputStream("tempdata.ser"); ObjectInputStream ois = new ObjectInputStream(fis); com.tedneward.Person ted = (com.tedneward.Person) ois.readObject(); ois.close(); assertEquals(ted.getFirstName(), "Ted"); assertEquals(ted.getSpouse().getFirstName(), "Charlotte"); // Clean up the file new File("tempdata.ser").delete(); } catch (Exception ex) { fail("Exception thrown during test: " + ex.toString()); } }}
No new or exciting things have been seen till now, but this is a good starting point. We will usePersonTo discover your potentialNoAboutJava object serializationFive things.
1. serialization allows refactoring
Serialization allows a certain number of class variants, even after reconstruction,ObjectInputStreamIt can still be read well.
Java Object SerializationThe key tasks for automatic management of specifications are:
- Add new fields to the class
- Change the field from static to non-static.
- Change the field from transient to non-transient
Depending on the degree of backward compatibility required, converting the field form from non-static to static or from non-transient to transient) or deleting the field requires additional message transmission.
Refactoring serialization class
Now that serialization allows refactoring, let's take a look at how to add the new fieldPersonClass.
As shown in listing 3,PersonV2In the originalPersonClass to introduce a new field indicating gender.
Listing 3. Add the new field to the serialized Person
enum Gender{ MALE, FEMALE}public class Person implements java.io.Serializable{ public Person(String fn, String ln, int a, Gender g) { this.firstName = fn; this.lastName = ln; this.age = a; this.gender = g; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Gender getGender() { return gender; } public int getAge() { return age; } public Person getSpouse() { return spouse; } public void setFirstName(String value) { firstName = value; } public void setLastName(String value) { lastName = value; } public void setGender(Gender value) { gender = value; } public void setAge(int value) { age = value; } public void setSpouse(Person value) { spouse = value; } public String toString() { return "[Person: firstName=" + firstName + " lastName=" + lastName + " gender=" + gender + " age=" + age + " spouse=" + spouse.getFirstName() + "]"; } private String firstName; private String lastName; private int age; private Person spouse; private Gender gender;}
Serialization uses a hash, which is calculated based on almost everything in the given source file-method name, field name, field type, access modification method, etc, serialization compares the hash value with the hash value in the serialized stream.
To make Java runtime believe that the two types are actually the same, the second and subsequent versionsPersonThe serialization version of hash must be the same as that of the first version. The hash Storage is private static final.serialVersionUIDField ). Therefore, we needserialVersionUIDField, which is based onPersonClass run JDKserialverCommand.
OncePersonOfserialVersionUID, Not only from the original objectPersonCreate serialized dataPersonV2When a new field appears in an object, the new field is set to the default value, and the most common is "null"). This can also be done in turn:PersonV2The data is obtained through deserialization.PersonThis is not surprising.