Serialization in Java

Source: Internet
Author: User
Tags object serialization serialization

The following is referenced from http://wiki.jikexueyuan.com/project/java/serialization.html:

Java provides a mechanism called object serialization, where objects are described as a series of data that includes objects and bytes about the type of object and the type of data stored in the object.

After a serialized object is written into a file, it can be read out in the file and deserialized into the type information and bytes representing the object, and its data can be used to recreate the object in memory.

The most impressive is that the entire process is JVM independent, meaning that an object can be serialized on a single platform and deserialized on a completely different platform.

The ObjectInputStream and ObjectOutputStream classes are streams that contain methods that serialize and deserialize objects.

The ObjectOutputStream class contains many write methods that write various data types, but one of these methods is particularly prominent:

 Public Final void throws IOException

The above method serializes an object and feeds it into the output stream. Similarly, the ObjectInputStream class contains the following methods for deserializing objects:

 Public Final throws IOException,  classnotfoundexception

This method retrieves the next object outside the stream and deserializes it. The return value is an object, so it needs to be converted to the correct data type.

To demonstrate how serialization works in Java, use the previous employee class. Assume that you have the following employee classes that implement serializable:

 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 + "" + addres   s); }}

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

    • Class must implement the Java.io.Serializable class.
    • All fields in the class must be serialized. If a field is not serialized, it must be marked as transient.

If you want to know if the Java standard class is serializable, you can view the documentation for the following class. The test is simple: If the class implements Java.io.Serializable, it is serializable; otherwise, it is not.

One, serialize an object

The ObjectOutputStream class is used to serialize an object. The following Serializedemo program instantiates an employee object and serializes it in a file.

When the program is executed, a file named Employee.ser is created. The program does not generate any output, but studies the code and tries to determine what the program is doing.

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

ImportJava.io.*; Public classserializedemo{ Public Static voidmain (String [] args) {Employee e=NewEmployee (); E.name= "Reyan Ali"; E.address= "Phokka Kuan, Ambehta Peer"; E.SSN= 11122333; E.number= 101; Try{FileOutputStream fileout=NewFileOutputStream ("/tmp/employee.ser"); ObjectOutputStream out=NewObjectOutputStream (fileout);         Out.writeobject (e);         Out.close ();         Fileout.close (); System.out.printf ("Serialized data is saved In/tmp/employee.ser"); }Catch(IOException i) {i.printstacktrace (); }   }}

Second, deserialize an object

The following Deserializedemo program deserializes an employee object that was created in the Serializedemo object. Study the program and try to determine its output:

ImportJava.io.*; Public classdeserializedemo{ Public Static voidmain (String [] args) {Employee e=NULL; Try{FileInputStream Filein=NewFileInputStream ("/tmp/employee.ser"); ObjectInputStream in=NewObjectInputStream (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); }}//this will produce the following results:deserialized Employee ... Name:reyan Aliaddress:phokka Kuan, Ambehta peerssn:0Number :101

Here are some important points to keep in mind:

    • The Try/catch block attempts to catch the classnotfoundexception declared by the ReadObject () method. To enable a JVM to deserialize an object, it must be able to find the byte code of the class. If the JVM cannot find a class during the deserialization of an object, it throws classnotfoundexception.
    • Note The return value of ReadObject () is coerced into a reference to the employee.
    • When the object is serialized, the value of the SSN field is 11122333, but because the field is ephemeral, the value is not fed into the output stream. The value of the SSN field for the deserialized employee object is 0.

Test Project: Https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test25

Serialization in 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.