Вопрос-ответ

What is object serialization?

Что такое сериализация объектов?

Что подразумевается под "сериализацией объектов"? Не могли бы вы, пожалуйста, объяснить это на нескольких примерах?

Переведено автоматически
Ответ 1

Сериализация - это преобразование объекта в серию байтов, так что объект можно легко сохранить в постоянное хранилище или передать потоковой передачей по каналу связи. Затем поток байтов может быть десериализован - преобразован в точную копию исходного объекта.

Ответ 2

Сериализацию можно рассматривать как процесс преобразования экземпляра объекта в последовательность байтов (которая может быть двоичной или нет, в зависимости от реализации).

Это очень полезно, когда вы хотите передать данные одного объекта по сети, например, из одной JVM в другую.

В Java механизм сериализации встроен в платформу, но вам необходимо реализовать интерфейс Serializable, чтобы сделать объект сериализуемым.

Вы также можете предотвратить сериализацию некоторых данных в вашем объекте, пометив атрибут как переходный.

Наконец, вы можете переопределить механизм по умолчанию и предоставить свой собственный; это может подойти в некоторых особых случаях. Для этого вы используете одну из скрытых функций java.

Важно отметить, что сериализуется "значение" объекта или содержимое, а не определение класса. Таким образом, методы не сериализуются.

Вот очень простой пример с комментариями, облегчающими его чтение:

import java.io.*;
import java.util.*;

// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {

// These attributes conform the "value" of the object.

// These two will be serialized;
private String aString = "The value of that string";
private int someInteger = 0;

// But this won't since it is marked as transient.
private transient List<File> unInterestingLongLongList;

// Main method to test.
public static void main( String [] args ) throws IOException {

// Create a sample object, that contains the default values.
SerializationSample instance = new SerializationSample();

// The "ObjectOutputStream" class has the default
// definition to serialize an object.
ObjectOutputStream oos = new ObjectOutputStream(
// By using "FileOutputStream" we will
// Write it to a File in the file system
// It could have been a Socket to another
// machine, a database, an in memory array, etc.
new FileOutputStream(new File("o.ser")));

// do the magic
oos.writeObject( instance );
// close the writing.
oos.close();
}
}

Когда мы запускаем эту программу, создается файл "o.ser", и мы можем увидеть, что произошло за ним.

Если мы изменим значение: someInteger на, например, целое число.MAX_VALUE, мы можем сравнить выходные данные, чтобы увидеть, в чем разница.

Here's a screenshot showing precisely that difference:

alt text

Can you spot the differences? ;)

There is an additional relevant field in Java serialization: The serialversionUID but I guess this is already too long to cover it.

Ответ 3

Daring to answer the 6-year-old question, adding just a very high-level understanding for people new to Java


What is Serialization?


Converting an object to bytes


What is Deserialization?


Converting bytes back to an object (Deserialization).


When is serialization used?


When we want to Persist the Object.
When we want the object to exist beyond the lifetime of the JVM.


Real World Example:


ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawal details will be serialized and sent to the server where the details are deserialized and used to perform operations.


How serialization is performed in java.



  1. Implement java.io.Serializable interface (marker interface so no method to implement).



  2. Persist the object: Use java.io.ObjectOutputStream class, a filter stream which is a wrapper around a lower-level byte stream (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side).




  • writeObject(<<instance>>) - to write an object

  • readObject() - to read an serialized Object


Remember:


When you serialize an object, only the object's state will be saved, not the object's class file or methods.

When you serialized a 2-byte object, you see 51 bytes serialized file.


Steps how the object is serialized and de-serialized.


Answer for: How did it convert to 51 bytes file?


  • First writes the serialization stream magic data (STREAM_MAGIC= "AC ED" and STREAM_VERSION=version of the JVM).

  • Then it writes out the metadata of the class associated with an instance (length of the class, the name of the class, serialVersionUID).

  • Then it recursively writes out the metadata of the superclass until it finds java.lang.Object.

  • Then starts with the actual data associated with the instance.

  • Finally writes the data of objects associated with the instance starting from metadata to the actual content.

you can also check my Youtube video explanation here

Edit : Reference link to read.

This will answer a few frequent questions:


  1. How not to serialize any field in the class.

    Ans: use transient keyword



  2. When child class is serialized does parent class get serialized?

    Ans: No, If a parent is not extending the Serializable interface parents field don't get serialized.



  3. When a parent is serialized does child class get serialized?

    Ans: Yes, by default child class also gets serialized.



  4. How to avoid child class from getting serialized?

    Ans: a. Override writeObject and readObject method and throw NotSerializableException.


    b. also you can mark all fields transient in child class.



  5. Some system-level classes such as Thread, OutputStream, and its subclasses, and Socket are not serializable.



Ответ 4

Serialization is taking a "live" object in memory and converting it to a format that can be stored somewhere (eg. in memory, on disk) and later "deserialized" back into a live object.

java serialization