Home Java javaTutorial Detailed explanation of object serialization and deserialization in Java

Detailed explanation of object serialization and deserialization in Java

Jan 18, 2017 am 10:42 AM

Serialization (Serialization) is the process of converting the state information of an object into a form that can be stored or transmitted. Generally, an object is stored in a storage medium, such as a file or memory buffer. During network transmission, it can be in byte or XML format. Byte or XML encoding formats can restore exactly equivalent objects. This reverse process is also called deserialization.
Serialization and Deserialization of Java Objects
In Java, we can create objects in a variety of ways, and we can reuse the object as long as the object is not recycled. However, these Java objects we create exist in the heap memory of the JVM. These objects may only exist when the JVM is running. Once the JVM stops running, the state of these objects is lost.
 But in real application scenarios, we need to persist these objects and be able to re-read the objects when needed. Java's object serialization can help us achieve this function.
The object serialization mechanism (object serialization) is a built-in object persistence method in the Java language. Through object serialization, the state of the object can be saved as a byte array, and this word can be used when necessary. The section array is converted into an object through deserialization. Object serialization makes it easy to convert between live objects and byte arrays (streams) in the JVM.
In Java, object serialization and deserialization are widely used in RMI (remote method invocation) and network transmission.
Relevant interfaces and classes
Java provides a set of convenient API support for developers to serialize and deserialize Java objects. These include the following interfaces and classes:

java.io.Serializable

java.io.Externalizable

ObjectOutput

ObjectInput

 ObjectOutputStream

 ObjectInputStream

 Serializable interface

The class implements the java.io.Serializable interface to enable its serialization function. A class that does not implement this interface will not be able to serialize or deserialize any of its state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and is used only to identify serializable semantics. (This interface has no methods and fields. Why can only objects of classes that implement this interface be serialized?)
When trying to serialize an object, if you encounter an object that does not support the Serializable interface. In this case, NotSerializableException will be thrown.
If the class to be serialized has a parent class, and you want to persist the variables defined in the parent class at the same time, the parent class should also integrate the java.io.Serializable interface.
The following is a class that implements the java.io.Serializable interface

package com.hollischaung.serialization.SerializableDemos;
import java.io.Serializable;
/**
* Created by hollis on 16/2/17.
* 实现Serializable接口
*/
public class User1 implements Serializable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Copy after login

Serialization and deserialization are performed through the following code

package com.hollischaung.serialization.SerializableDemos;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
/**
* Created by hollis on 16/2/17.
* SerializableDemo1 结合SerializableDemo2说明 一个类要想被序列化必须实现Serializable接口
*/
public class SerializableDemo1 {
public static void main(String[] args) {
//Initializes The Object
User1 user = new User1();
user.setName("hollis");
user.setAge(23);
System.out.println(user);
//Write Obj to File
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(user);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(oos);
}
//Read Obj from File
File file = new File("tempFile");
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
User1 newUser = (User1) ois.readObject();
System.out.println(newUser);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(ois);
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//OutPut:
//User{name='hollis', age=23}
//User{name='hollis', age=23}
Copy after login

The above is the entire content of this article, I hope it will be helpful to It will be helpful for everyone to learn object serialization and deserialization in Java.

For more detailed articles related to object serialization and deserialization in Java, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

When Tomcat loads Spring-Web modules, does the SPI mechanism really destroy the visibility principle of Java class loaders? When Tomcat loads Spring-Web modules, does the SPI mechanism really destroy the visibility principle of Java class loaders? Apr 19, 2025 pm 02:18 PM

Analysis of class loading behavior of SPI mechanism when Tomcat loads Spring-Web modules. Tomcat is used to discover and use the Servle provided by Spring-Web when loading Spring-Web modules...

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

See all articles