What is the purpose of the Serializable interface?

Asked

Viewed 21,968 times

31

Example of implementation:

 public class MyClass implements Serializable{
     private static final long serialVersionUID = 1L;
 }
  • https://camilolopes.wordpress.com/2008/06/04/serializacao-em-java/

3 answers

48


Serialization means saving the current state of the objects in binary format to your computer, so this state can be recovered later by recreating the object in memory just as it was at the time of its serialization.

See illustration:

inserir a descrição da imagem aqui

Source: State of the art - Nuances about serialization of heritage objects in Java

In order to be able to serialize and deserialize an object, it is mandatory that your class implements the interface Serializable.

An example of a code that serializes an object:

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 the same object:

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

Upshot:

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

Source: Tutorials Point

  • 16

    I came here to give +1 just for the photo of the inflatable bug.

  • Which isn’t very accurate, by the way. The animal should be disassembled into its component parts, which should pass through a duct, to be reassembled on the other side. : P

  • It is nice to mention for example that to queue objects, clone (apache Commons) you need to implement the Serializable interface

  • Para que seja possível serializar e desserializar um objeto, é obrigatório que a sua classe implemente a interface Serializable. IS NOT REQUIRED.

  • @Could Davidschrammel show me how to serialize a class that does not implement the Serializable interface? I went in search of a source to corroborate my statement and the last link of my reply has this text: "The class must implement the java.io.Serializable interface." I don’t understand what you’re saying.

  • The worst is that in the background the image is backwards. The serialized version is often more inflated than the memory version :) But I understood the intention.

  • @bigown heheh.. Well, the intention is just to say that the object stays in a state that serves to be guarded, and not to be used. I never checked the size of an object in memory to know its size, but the intention is this ;) I’m glad you understood

  • 1

    @Math Perhaps it is using the term "serialize" in a more generic way, for example when you turn an object into a JSON string, which is also a form of serialization, although it does not use the mechanism provided by Java. Using the Java engine not only the class should implement Serializable, as you said, as well as the classes of all your attributes, and the attributes of your attributes and so on.

  • 1

    @Math there are many ways to serialize an object, particularly I use a solution that consists of serializing an instance of an object in a json and retrieve the instance using Reflection; but this can be implemented in the hand.

Show 4 more comments

12

It gives the class the ability to produce a format in which the object data is used externally to the code, in general it is persisted in some form of temporary or permanent storage or is transmitted to another resource.

This format can be text or binary in several standard or proprietary variants. It is very common to use JSON or XML.

Deserialization is the opposite process. Take data in a known format and place the data found in the serialized state within the class members by creating or updating an object.

Implementing this interface is not very trivial, although it seems to be. It is common to use a ready-made solution that uses reflection. It is common to serialize expose private parts of the class, which is often not desirable, so need care, on the other hand without private parts may not have all that is needed.

  • json , xml also?

  • These are the most common formats when serializing to text.

  • blz thanks for the return :)

7

Adding the serializable interface makes it possible to transform the object into a format that can be saved in a file. For example, to use an Objectoutputstream and save an object to a disk file you will need to implement this interface.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.