Java object serialization NIO NIO2 details and parsing

  • 2020-06-07 04:29:35
  • OfStack

Java object serialization NIO NIO2 details and parsing

Summary:

Object serialization

The object serialization mechanism allows an Java object in memory to be converted to a platform-independent 2-base stream that can be saved to disk or transferred over the network. Other programs can retrieve the 2-base stream and restore it to the original Java object. The serialization mechanism allows objects to exist independently of the program

Meaning and meaning of serialization

serialization

The serialization mechanism allows objects to exist independently of the program

Serialization (Serialize) refers to the writing of an java object to the IO stream, and the corresponding deserialization of the object (Deserialize) refers to the recovery of the java object from the IO stream

If you want an object to support serialization, its classes must be serializable (serializable). For a class to be serializable, you must implement one of two interfaces:

Serializable: Tag the interface without implementing any methods, just to indicate that an instance of the class is serializable Externalizable

All objects transferred over the network should be serializable, otherwise an exception will occur; All classes of objects that need to be saved to disk must be serializable; Each JavaBean class created by the program implements Serializable;

Serialization is achieved using object flows

The program can serialize the object by following two steps:

1. Create an ObjectOutputStream. The output stream is a processing stream, so it must be based on other node flows


//  To create a ObjectOutputStream The output stream 
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"));

2. Call the writeObject method on the ObjectOutputStream object to output the serializable object


//  will 1 a Person Object to output to an output stream 
oos.writeObject(per);

Define an NbaPlayer class that implements the Serializable interface, which identifies the object of the class as serializable


public class NbaPlayer implements java.io.Serializable
{
  private String name;
  private int number;
  //  Note that no parameterless constructor is provided here !
  public NbaPlayer(String name, int number)
  {
    System.out.println(" Constructor with parameters ");
    this.name = name;
    this.number = number;
  }

  // name the setter and getter methods 
  public void setName(String name)
  {
    this.name = name;
  }
  public String getName()
  {
    return this.name;
  }

  // number the setter and getter methods 
  public void setNumber(int number)
  {
    this.number = number;
  }
  public int getNumber()
  {
    return this.number;
  }
}

Use ObjectOutputStream to write 1 NbaPlayer object to a disk file


import java.io.*;

public class WriteObject
{
  public static void main(String[] args)
  {
    try(
      //  create 1 a ObjectOutputStream The output stream 
      ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("object.txt")))
    {
      NbaPlayer player = new NbaPlayer(" Westbrook ", 0);
      //  will player Object writes to the output stream 
      oos.writeObject(player);
    }
    catch (IOException ex)
    {
      ex.printStackTrace();
    }
  }
}

deserialization

To recover an Java object from a 2-base stream, you need to use deserialization, which the program can do by following two steps:

1. Create an ObjectInputStream input stream. This input stream is a processing stream, so it must be built on top of other node flows


//  To create a ObjectInputStream The output stream 
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));

2. The readObject() method of the ObjectInputStream object is called to read the object in the stream. This method returns 1 Java object of type Object, which can be cast to its real type


//  Read from the input stream 1 a Java Object and casts it to Person class 
Person p = (Person)ois.readObject();

Steps to read the NbaPlayer object from the ES78en.txt file


import java.io.*;
public class ReadObject
{
  public static void main(String[] args)
  {
    try(
      //  create 1 a ObjectInputStream The input stream 
      ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream("object.txt")))
    {
      //  Read from the input stream 1 a Java Object and casts it to NbaPlayer class 
      NbaPlayer player = (NbaPlayer)ois.readObject();
      System.out.println(" The name is: " + player.getName()
        + "\n Number is: " + player.getNumber());
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
  }
}

The deserialization reads only the data of the Java object, not the Java class. Therefore, when deserializing the Java object, the class file of the Java object must be provided, otherwise an ClassNotFoundException exception will be thrown. The deserialization mechanism does not require the constructor to initialize the Java object

If multiple Java objects were written to a file using the serialization mechanism, the recovery objects using the deserialization mechanism must be read in the order in which they were actually written. When a serializable class has multiple superclasses (both direct and indirect), these superclasses are either parameterless constructors or also serializable - otherwise deserialization throws an InvalidClassException exception. If the parent class is non-serializable and is just a constructor with no arguments, the value of Field defined by the parent class will not be serialized into a base 2 stream

Serialization of object references

If the Field type of a class is not the base type or String type, but another reference type, then the reference type must be serializable, or the class that USES Field of that type is also non-serializable


public class AllStar implements java.io.Serializable
{
  private String name;
  private NbaPlayer player;
  public AllStar(String name, NbaPlayer player)
  {
    this.name = name;
    this.player = player;
  }
  //  Omitted here name and player the setter and getter methods 

  // name the setter and getter methods 
  public String getName()
  {
    return this.name;
  }

  public void setName(String name)
  {
    this.name = name;
  }

  // player the setter and getter methods 
  public NbaPlayer getPlayer() 
  {
    return player;
  }

  public void setPlayer(NbaPlayer player) 
  {
    this.player = player;
  }
}

Java's special serialization algorithm

All objects saved to disk have a serialization number When a program tries to serialize an object, it first checks to see if the object has been serialized. Only if the object has never been serialized (in this case) will the system convert the object into a sequence of bytes and output it If an object has been serialized, the program simply outputs a serialization number instead of re-serializing the object

import java.io.*;
public class WriteAllStar
{
  public static void main(String[] args)
  {
    try(
      //  create 1 a ObjectOutputStream The output stream 
      ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("allStar.txt")))
    {
      NbaPlayer player = new NbaPlayer(" James Harden ", 13);
      AllStar allStar1 = new AllStar(" Western Conference All-star ", player);
      AllStar allStar2 = new AllStar(" Starting guard ", player);
      //  In turn 4 Five objects write to the output stream 
      oos.writeObject(allStar1);
      oos.writeObject(allStar2);
      oos.writeObject(player);
      oos.writeObject(allStar2);
    }
    catch (IOException ex)
    {
      ex.printStackTrace();
    }
  }
}

Of the four objects that were written to the output stream, only three were actually serialized, and the player references of the two AllStar objects in the sequence were actually the same NbaPlayer object. The following program reads the objects in the serialized file


import java.io.*;
public class ReadAllStar
{
  public static void main(String[] args)
  {
    try(
      //  create 1 a ObjectInputStream The output stream 
      ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream("allStar.txt")))
    {
      //  In turn to read ObjectInputStream In the input stream 4 An object 
      AllStar star1 = (AllStar)ois.readObject();
      AllStar star2 = (AllStar)ois.readObject();
      NbaPlayer player = (NbaPlayer)ois.readObject();
      AllStar star3 = (AllStar)ois.readObject();
      //  The output true
      System.out.println("star1 the player References and player Whether the same: "
        + (star1.getPlayer() == player));
      //  The output true
      System.out.println("star2 the player References and player Whether the same: "
        + (star2.getPlayer() == player));
      //  The output true
      System.out.println("star2 and star3 Whether the same 1 Object: "
        + (star2 == star3));
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
  }
}

If the same variable Java object is serialized multiple times, the Java object is converted to a sequence of bytes and output only on the first serialization

When using the Java serialization mechanism to serialize mutable objects, only the first call to the WriteObject() method to output the object is converted to a sequence of bytes and written to ObjectOutputStream; When the WriteObject() method is called again to output the object, the changed instance variable will not be output, even if the object's instance variable is changed in a later program


//  will 1 a Person Object to output to an output stream 
oos.writeObject(per);
0

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: