Java provides a mechanism called object serialization. It refers to an object that can be described as a byte sequence. This byte sequence not only contains the data of this object, but also contains some other information: object Type and Data Type stored in the object.
When a serialized object is written to a file, it can be read from the file, that is, deserialization. Data Types, bytes, and data can be combined to generate an object in the memory.
The most impressive thing is that the entire process is unrelated to JVM, which means that deserialization can be performed on another completely different platform after serialization on this platform.
The objectinputstream and objectoutputstream classes contain methods for serialization and deserialization.
Objectoutputstream contains many write methods for different types, but there is a method that is particularly prominent.
Public final void writeobject (Object X) throws ioexception
The above method serializes an object and sends it to the output stream.
Similarly, the objectinputstream class contains the following methods for deserializing an object.
Public final object readobject () throws ioexception, classnotfoundexception
This method retrieves the next object stream and deserializes it. The returned value belongs to the object type, so you need to convert it to the appropriate data type.
Let's take a look at an example. Here I will not translate it, but it will be displayed in English:
To demonstrate how serialization works in Java, I am going to use
Employee class that we discussed early on in the book. Suppose that we
Have the following employee class, which implements the serializable
Interface:
public class Employee implements java.io.Serializable { public String name; public String address; public int transient SSN; public int number;
public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); }
}
|
Notice that for a class to be serialized successfully, two conditions must be met:
The class must implement the java. Io. serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
If you are curious to know if a Java satandard class is serializable
Or not, check the documentation for the class. The test is simple: if
The class implements java. Io. serializable, then it is serializable;
Otherwise, it's not.
Serializing an object:
The objectoutputstream class is used to serialize an object.
Following serializedemo program instantiates an employee object and
Serializes it to a file.
When the program is done executing, a file named employee. SER is
Created. The program does not generate any output, but study the code
And try to determine what the program is doing.
Note:
When serializing an object to a file, the standard convention in Java is to give the file. Ser
Extension.
import java.io.*;
public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =new FileOutputStream("employee.ser");
ObjectOutputStream out =new ObjectOutputStream(fileOut);(1)
out.writeObject(e);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
}
(1) The function is to create a specified object output stream, that is, the created out object for converting an object to a stream is a special object, it calls writeobject (Object o) to write the serialized stream to the file stream. The reason why it has this function is that you pass a file stream parameter to it, so it has this function.
Objectoutputstream (Java 2 platform SE 6)
Objectoutputstream
public ObjectOutputStream
(OutputStream
out) throws IOException
-
Create
Objectoutputstream. This constructor writes the part of the serialized stream to the bottom layer. The caller can refresh the stream immediately to ensure that it is used to receive
The objectinputstreams constructor is not blocked.
If the security manager is installed, You can override objectoutputstream. putfields or
When the constructor of the subclass of the objectoutputstream. writeunshared method is called directly or indirectly
"Enablesubclassimplementation" serializablepermission.
-
Parameters:
-
out
-Output stream to write data
-
Throw:
-
IOException
-If I/O occurs when the stream is written
Error
-
SecurityException
-
If the untrusted subclass illegally overrides the security-sensitive method
-
NullPointerException
-Ifout
Isnull
Deserializing an object:
The following deserializedemo program deserializes the employee
Object created in the serializedemo program. Study the program and try
To determine its output:
import java.io.*;
public class DeserializeDemo
{ public static void main(String [] args) { Employee e = null;
try { FileInputStream fileIn =new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println(.Employee class not found.); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); } }
|
This wowould produce following result:
Deserialized Employee... Name: Reyan Ali Address:Phokka Kuan, Ambehta Peer SSN: 0 Number:101
|
Here are following important points to be noted:
The try/Catch Block tries to catch a classnotfoundexception,
Which is declared by the readobject () method. For a JVM to be able
Deserialize an object, it must be able to find the bytecode for
Class. If the JVM can't find a class during the deserialization of
Object, it throws a classnotfoundexception.
Notice that the return value of readobject () is cast to an employee reference.
The value of the SSN field was 11122333 when the object was
Serialized, but because the field is transient, this value was not sent
To the output stream. The ssn field of the deserialized employee object
Is 0.