Home  >  Article  >  Java  >  How to implement serialization in java

How to implement serialization in java

(*-*)浩
(*-*)浩Original
2019-11-14 11:47:162524browse

Serialization is a mechanism used to process object streams. The so-called object stream is to stream the content of the object.

How to implement serialization in java

You can read and write streamed objects, and you can also transmit streamed objects between networks. Serialization is to solve problems that may arise during object stream read and write operations (if serialization is not performed, data may be out of order). (Recommended learning: java course)

To implement serialization, a class needs to implement the Serializable interface. This interface is an identifying interface that marks the object of this class as being Serialized, then use an output stream to construct an object output stream and write out the implementation object (that is, save its state) through the writeObject(Object obj) method

If you need to deserialize, you can use an input stream to create an object input stream, and then read the object from the stream through the readObject method. In addition to achieving object persistence, serialization can also be used for deep cloning of objects.

To demonstrate how serialization works in Java, I will use the Employee class mentioned in the previous tutorial. Suppose we define the following Employee class, which implements the Serializable interface.

public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}

Please note that for an object of a class to be serialized successfully, it must meet two conditions:

The class must implement the java.io.Serializable interface.

All properties of this class must be serializable. If a property is not serializable, the property must be marked as ephemeral.

If you want to know whether a Java standard class is serializable, check the documentation for that class. Checking whether an instance of a class can be serialized is very simple, just check whether the class implements the java.io.Serializable interface.

The above is the detailed content of How to implement serialization in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn