What is object serialization?

2018-12-31 03:50发布

What is meant by "object serialization"? Can you please explain it with some examples?

13条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 04:17

|*| Serializing a class : Converting an object to bytes and bytes back to object (Deserialization).

class NamCls implements Serializable
{
    int NumVar;
    String NamVar;
}

|=> Object-Serialization is process of converting the state of an object into steam of bytes.

  • |-> Implement when you want the object to exist beyond the lifetime of the JVM.
  • |-> Serialized Object can be stored in Database.
  • |-> Serializable-objects cannot be read and understood by humans so we can acheive security.

|=> Object-Deserialization is the process of getting the state of an object and store it into an object(java.lang.Object).

  • |-> Before storing its state it checks whether serialVersionUID form input-file/network and .class file serialVersionUID are same.
    &nbsp&nbspIf not throw java.io.InvalidClassException.

|=> A Java object is only serializable, if its class or any of its superclasses

  • implements either the java.io.Serializable interface or
  • its subinterface, java.io.Externalizable.

|=> Static fields in a class cannot be serialized.

class NamCls implements Serializable
{
    int NumVar;
    static String NamVar = "I won't be serializable";;
}

|=> If you do not want to serialise a variable of a class use transient keyword

class NamCls implements Serializable
{
    int NumVar;
    transient String NamVar;
}

|=> If a class implements serializable then all its sub classes will also be serializable.

|=> If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case,
NotSerializableException is thrown at runtime.

查看更多
只若初见
3楼-- · 2018-12-31 04:21

I liked the way @OscarRyz presents. Although here i am continuing the story of serialization which was originally written by @amitgupta.

Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything became fine.

查看更多
与君花间醉酒
4楼-- · 2018-12-31 04:23

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 04:24

Serialization is the process of turning a Java object into byte array and then back into object again with its preserved state. Useful for various things like sending objects over network or caching things to disk.

Read more from this short article which explains programming part of the process quite well and then move over to to Serializable javadoc. You may also be interested in reading this related question.

查看更多
低头抚发
6楼-- · 2018-12-31 04:24

Return the file as an Object : http://www.tutorialspoint.com/java/java_serialization.htm

        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();
              }
           }
        }

    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);
        }
    }
查看更多
十年一品温如言
7楼-- · 2018-12-31 04:31

Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects state are converted into a byte stream. This type of the file can not be understood by the user. It is a special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object.

The object to be serialized must implement java.io.Serializable Interface. Default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.

class ObjectOutputStream extends java.io.OutputStream implements ObjectOutput,

ObjectOutput interface extends the DataOutput interface and adds methods for serializing objects and writing bytes to the file. The ObjectOutputStream extends java.io.OutputStream and implements ObjectOutput interface. It serializes objects, arrays, and other values to a stream. Thus the constructor of ObjectOutputStream is written as:

ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));

Above code has been used to create the instance of the ObjectOutput class with the ObjectOutputStream( ) constructor which takes the instance of the FileOuputStream as a parameter.

The ObjectOutput interface is used by implementing the ObjectOutputStream class. The ObjectOutputStream is constructed to serialize the object.

Deserializing an Object in java

The opposite operation of the serialization is called deserialization i.e. to extract the data from a series of bytes is s known as deserialization which is also called inflating or unmarshalling.

ObjectInputStream extends java.io.InputStream and implements ObjectInput interface. It deserializes objects, arrays, and other values from an input stream. Thus the constructor of ObjectInputStream is written as:

ObjectInputStream obj = new ObjectInputStream(new FileInputStream(f));

Above code of the program creates the instance of the ObjectInputStream class to deserialize that file which had been serialized by the ObjectInputStream class. The above code creates the instance using the instance of the FileInputStream class which holds the specified file object which has to be deserialized because the ObjectInputStream() constructor needs the input stream.

查看更多
登录 后发表回答