Serialization
Java serialization technology allows you to write the state of an object into a Byte stream, and read the data in the Byte stream from other places to reconstruct an identical object.
When two processes perform remote communication, they can send different types of data to each other. Regardless of the type of data, it is transmitted on the network in the form of binary sequence. The sender needs to convert the Java object into a byte sequence before it can be transmitted over the network. The receiver needs to restore the byte sequence to a Java object.
The process of converting a Java object to a byte sequence is called object serialization.
The process of restoring a byte sequence to a Java object is called object deserialization.
1. serialization Purpose
Object serialization can be used to save the current working state of the application, and will be automatically restored to the last running state at the next startup.
Object serialization has two main purposes:
(A) the object's byte sequence is permanently stored on the hard disk, usually stored in a file;
(B) Transmit the byte sequence of objects over the network.
2. serialization implementation
(1) serialization API in JDK class library
Java. io. ObjectOutputStream represents the Object output stream. Its writeObject (Object obj) method can serialize the obj Object specified by the parameter and write the obtained byte sequence to a target output stream.
Java. io. ObjectInputStream indicates the object input stream. Its readObject () method reads byte sequences from a source input stream, deserializes them into an object, and returns it.
Only objects of classes that implement the Serializable and Externalizable interfaces can be serialized. The Externalizable interface inherits from the Serializable interface. classes that implement the Externalizable interface completely control the serialization behavior. classes that only implement the Serializable interface can adopt the default serialization method.
(2) Object serialization and deserialization
The Serializable interface is implemented for the class to be serialized. There is no method to implement this interface. implements Serializable only aims to mark that the object can be serialized and then uses an output stream (such: fileOutputStream) to construct an ObjectOutputStream (Object stream) Object. Then, you can use the writeObject (Object obj) method of the ObjectOutputStream Object to write (that is, save its status) the Object whose parameter is obj ), the input stream is used for recovery.
Object serialization includes the following steps:
(A) Create an object output stream, which can wrap a target output stream of another type, such as a file output stream;
(B) write an object using the writeObject () method of the object output stream.
The steps for object deserialization are as follows:
(A) Create an object input stream, which can wrap a source input stream of another type, such as a file input stream;
(B) read the object through the readObject () method of the object input stream.
Let's look at a corresponding example. The class content is as follows:
Java code
- ImportJava. io .*;
- ImportJava. util. Date;
- Public ClassObjectSaver {
- Public Static VoidMain (String [] args)ThrowsException {
- ObjectOutputStream out =NewObjectOutputStream
- (NewFileOutputStream ("D :""ObjectFile. obj"));
- // Serialize the object
- Customer customer =NewCustomer ("A honey fruit",24);
- Out. writeObject ("Hello! ");
- Out. writeObject (NewDate ());
- Out. writeObject (customer );
- Out. writeInt (123);// Write basic data
- Out. close ();
- // Deserialization object
- ObjectInputStream in =NewObjectInputStream
- (NewFileInputStream ("D :""ObjectFile. obj"));
- System. out. println ("Obj1 ="+ (String) in. readObject ());
- System. out. println ("Obj2 ="+ (Date) in. readObject ());
- Customer obj3 = (Customer) in. readObject ();
- System. out. println ("Obj3 ="+ Obj3 );
- IntObj4 = in. readInt ();
- System. out. println ("Obj4 ="+ Obj4 );
- In. close ();
- }
- }
- ClassCustomerImplementsSerializable {
- PrivateString name;
- Private IntAge;
- PublicCustomer (String name,IntAge ){
- This. Name = name;
- This. Age = age;
- }
- PublicString toString (){
- Return "Name ="+ Name +", Age ="+ Age;
- }
- }
- ImportJava. io .*;
- ImportJava. util. Date;
- Public ClassObjectSaver {
- Public Static VoidMain (String [] args)ThrowsException {
- ObjectOutputStream out =NewObjectOutputStream
- (NewFileOutputStream ("D :""ObjectFile. obj"));
- // Serialize the object
- Customer customer =NewCustomer ("A honey fruit",24);
- Out. writeObject ("Hello! ");
- Out. writeObject (NewDate ());
- Out. writeObject (customer );
- Out. writeInt (123);// Write basic data
- Out. close ();
- // Deserialization object
- ObjectInputStream in =NewObjectInputStream
- (NewFileInputStream ("D :""ObjectFile. obj"));
- System. out. println ("Obj1 ="+ (String) in. readObject ());
- System. out. println ("Obj2 ="+ (Date) in. readObject ());
- Customer obj3 = (Customer) in. readObject ();
- System. out. println ("Obj3 ="+ Obj3 );
- IntObj4 = in. readInt ();
- System. out. println ("Obj4 ="+ Obj4 );
- In. close ();
- }
- }
- ClassCustomerImplementsSerializable {
- PrivateString name;
- Private IntAge;
- PublicCustomer (String name,IntAge ){
- This. Name = name;
- This. Age = age;
- }
- PublicString toString (){
- Return "Name ="+ Name +", Age ="+ Age;
- }
- }
The output result is as follows:
Java code
- Obj1 = hello!
- Obj2 = Sat Sep26 22:02:21CST2010
- Obj3 = name = honey fruit, age =24
- Obj4 =123
- Obj1 = hello!
- Obj2 = Sat Sep26 22:02:21CST2010
- Obj3 = name = honey fruit, age =24
- Obj4 =123
Therefore, the example is simple and will not be detailed here.
3. serialVersionUID:
To maintain version compatibility during serialization, that is, during version upgrade, deserialization still maintains the uniqueness of objects.
There are two generation methods:
One is the default 1L, for example:
Java code
- private static final long serialVersionUID = 1L;
- private static final long serialVersionUID = 1L;
One is to generate a 64-bit hash field based on the class name, Interface Name, member method, and attribute. For example:
Java code
- private static final long serialVersionUID = xxxxL;
- private static final long serialVersionUID = xxxxL;
Ii. Clone
Sometimes you want to get a replica of an object. The object of this replica is a clone of the original object. Changes in the copy object will not cause changes in the original object entity. Such a copy is called a clone object of the original object entity or a clone object for short.
1. Shortest replication (Shortest clone)
Concept: all variables of the Copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, the shortest copy only copies the objects to be considered, rather than the objects referenced by the shortest copy.
Method: class implements Cloneable. Then rewrite the clone () method and call super. clone () in the clone () method. There are no other operations.
2. Deep replication (deep cloning)
Concept: all variables of the Copied object contain the same value as the original object, except those variables that reference other objects. Variables that reference other objects will point to new objects that have been copied, instead of the original referenced objects. In other words, deep replication copies all the objects referenced by the objects to be copied.
Method:
(1) class implements Cloneable, then rewrite the clone () method, call super. clone () in the clone () method, and then clone the object referred to by the referenced variable.
(2) serialization: Write the object to the object output stream. The object read back from the object input stream is a deep clone of the original object.
- Java serialization mechanism and Principle
- Java Socket Communication serialization and deserialization code
- Detailed description of Java input data streams
- Java in-depth file and stream
- Java object serialization