Serialization of Runoob_java

Source: Internet
Author: User
Tags object serialization

Java serialization

Java provides a mechanism for object serialization, in which an object can be represented as a sequence of bytes that includes the object's data, information about the type of the object, and the type of data stored in the object.

After a serialized object is written to a file, it can be read from the file and deserialized, that is, the object's type information, the object's data, and the data type in the object can be used to create a new object in memory.

The entire process is independent of the Java virtual machine (JVM), which means that objects serialized on one platform can deserialize the object on another completely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level data streams that contain methods for serializing and deserializing objects.

The ObjectOutputStream class contains many write methods to write various data types, but a special method exception:

 
Public final void WriteObject (Object x) throws IOException

The above method serializes an object and sends it to the output stream. A similar ObjectInputStream class contains the following methods for deserializing an object:

 
Public final Object ReadObject () throws IOException,                                  classnotfoundexception

The method takes the next object out of the stream and deserializes the object. It has a return value of object, so you need to convert it to the appropriate data type.

To demonstrate how serialization works in Java, I'll use the employee class mentioned in the previous tutorial, assuming we define the following employee class, which implements the serializable interface.

Employee.java File Code: 
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);}   }

Note that for a class object to be serialized successfully, two conditions must be met:

The class must implement the Java.io.Serializable object.

All properties of the class must be serializable. If there is a property that is not serializable, the attribute must be noted to be short-lived.

If you want to know if a Java standard class is serializable, see the documentation for that class. It is very simple to verify that an instance of a class can be serialized, just to see if the class implements the Java.io.Serializable interface.

Serializing objects

The ObjectOutputStream class is used to serialize an object, as the following Serializedemo example instantiates an Employee object and serializes the object into a file.

After the program executes, a file named Employee.ser is created. The program does not have any output, but you can read through the code to understand the role of the program.

Note: when serializing an object to a file, the standard convention in Java is to give the file a. ser extension.

Serializedemo.java File Code: 
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 ("/tmp/employee.ser");         ObjectOutputStream out = new ObjectOutputStream (fileout);         Out.writeobject (e);         Out.close ();         Fileout.close ();         System.out.printf ("Serialized data is saved In/tmp/employee.ser");      } catch (IOException i)      {          i.printstacktrace ();}}   }

Deserializing objects

The following Deserializedemo program instance is deserialized and/tmp/employee.ser stores the employee object.

Deserializedemo.java File Code: 
Import java.io.*; public class deserializedemo{public   static void Main (String [] args)   {      Employee e = null;      Try      {         FileInputStream Filein = new FileInputStream ("/tmp/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);}    }

The results of the above program compilation run are as follows:

DeserializedEmployee... Name:reyanAliAddress:phokkaKuan,ambehtaPeerSSN: 0number:101               

Here are the key points to note:

The Try/catch code block in the ReadObject () method attempts to catch the classnotfoundexception exception. For a JVM to deserialize an object, it must be a class that can find the bytecode. If the JVM cannot find the class during deserialization of the object, a ClassNotFoundException exception is thrown.

Note that the return value of the ReadObject () method is converted to an Employee reference.

When the object is serialized, the value of the property SSN is 111222333, but because the property is ephemeral, the value is not sent to the output stream. So the SSN property of the Employee object after deserialization is 0.

Serialization of Runoob_java

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.