Java object serialization

Source: Internet
Author: User

The object is serialized to save the object to a disk or transmit it over the network. The object serialization mechanism allows the conversion layer of java objects in memory to binary streams unrelated to the platform. If an object is to be serialized, it must inherit the Serializable or Externalizable interfaces. Once these two interfaces are inherited, such objects can be serialized, in addition, each object will be serialized once in the java serialization mechanism. If another class object is referenced in an object, the object of this class will also be serialized, therefore, you must ensure that this class is also a serializable class. However, if you want to disable the serialization of a field in a class, you can add the key word transient in the field declaration step 1. create an ObjectOutputStream to process the stream 2. call the method writeObject () to output the serializable object.

try {      ObjectOutputStream obj = new ObjectOutputStream(              new FileOutputStream("1.txt"));      Pserson pe=new Pserson("xiong", 23);      obj.writeObject(pe);          } catch (Exception e) {      e.printStackTrace();  }  

 

If you want to restore a Java object, deserialization is required. During deserialization, the basic steps must be read in the write order: 1. create an ObectInputStream to process the stream 2. call its method readObject () to read objects in the stream
ObjectInputStream obj = new ObjectInputStream(new FileInputStream(                      "1.txt"));              Pserson pe = (Pserson) obj.readObject();              System.out.println("name:" + pe.getName() + "  age:" + pe.getAge());  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.