Details of object serialization and deserialization in Java

  • 2020-05-05 11:17:46
  • OfStack

            serialization (Serialization) is the process of converting the state information of an object into a form that can be stored or transferred. An object is typically stored in a storage medium, such as a file or memory buffer. During network transmission, it can be in the form of bytes or XML. The byte or XML encoding format can restore exactly the same object. This reverse process is also known as deserializing .
Serialization and deserialization of Java objects
In Java, we can create objects in a variety of ways, and we can reuse objects as long as they are not recycled. However, the Java objects we created all exist in JVM's heap memory. These objects can only exist if JVM is running. Once JVM stops running, the state of these objects is lost.
But in a real application scenario, we would need to persist these objects and be able to re-read them as needed. Java's object serialization can help us achieve this.
Object serialization mechanism (object serialization) is an object persistence method built into Java language. Through object serialization, the state of an object can be saved as an array of bytes, and the byte array can be deserialized into an object if necessary. Object serialization can be easily converted between active objects and byte arrays (streams) in JVM.
In Java, object serialization and deserialization are widely used in RMI(remote method call) and network transport.
Related interfaces and classes
Java provides a convenient set of API support for developers to serialize and deserialize Java objects. This includes the following interfaces and classes:

                java.io.Serializable java io Externalizable ObjectOutput ObjectInput ObjectOutputStream ObjectOutputStream Serializable

Class to enable its serialization by implementing the java.io.Serializable interface. Classes that do not implement this interface will not be able to serialize or deserialize any of their state. All subtypes of serializable classes are themselves serializable. The serialization interface has no methods or fields and is only used to identify serializable semantics. The interface has no methods or fields, so why should only objects of the class that implements the interface be serialized?
When trying to serialize an object, if you encounter an object that does not support the Serializable interface. In this case, NotSerializableException is thrown.
If the class to be serialized has a parent class, the parent class should also integrate the java.io.Serializable interface in order to persist variables defined in the parent class as well.
Below is a class
that implements the java.io.Serializable interface


package com.hollischaung.serialization.SerializableDemos;
import java.io.Serializable;
/**
* Created by hollis on 16/2/17.
*  implementation Serializable interface 
*/
public class User1 implements Serializable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

Serialize and deserialize
with the following code


package com.hollischaung.serialization.SerializableDemos;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
/**
* Created by hollis on 16/2/17.
* SerializableDemo1  In combination with SerializableDemo2 instructions   A class must be implemented in order to be serialized Serializable interface 
*/
public class SerializableDemo1 {
public static void main(String[] args) {
//Initializes The Object
User1 user = new User1();
user.setName("hollis");
user.setAge(23);
System.out.println(user);
//Write Obj to File
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(user);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(oos);
}
//Read Obj from File
File file = new File("tempFile");
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
User1 newUser = (User1) ois.readObject();
System.out.println(newUser);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(ois);
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//OutPut:
//User{name='hollis', age=23}
//User{name='hollis', age=23}

That's all for this article, which I hope will help you learn about object serialization and deserialization in Java.


Related articles: