首页  >  文章  >  Java  >  Java 中的序列化

Java 中的序列化

王林
王林原创
2024-08-30 16:06:52789浏览

Java中的序列化是一种将对象的状态转换为字节流的机制。反序列化是其逆过程。通过反序列化,可以从字节流在内存中创建实际的 Java 对象。这种机制持续存在于对象中。通过序列化创建的字节流不依赖于任何平台。任何其他平台都可以反序列化在一个平台上序列化的对象,不会出现问题。

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

因此,序列化和反序列化的整个过程是独立于JVM的。要序列化类对象,必须实现 java.io.Serialized 接口。 Java中的Serializing是一个标记接口。它没有要实现的字段或方法。此过程使类可序列化,类似于选择加入过程。

Java中的序列化是由ObjectInputStream和ObjectOutputStream这两个类实现的。所需要的只是对它们进行包装,以便将它们保存到文件或通过网络发送。

Java 序列化的概念

上一节提到的序列化类ObjectOutputStream包含多种用于写入各种数据类型的写入方法,但其中一种方法是最流行的。

public final void writeObject( Object x ) throws IOException

可以使用上面的方法来序列化一个对象。此方法还将其发送到输出流。同样,ObjectInputStream类包含对象反序列化的方法。

public final Object readObject() throws IOException, ClassNotFoundException

反序列化方法从流中检索对象并对其进行反序列化。返回值又是一个对象,因此所需要做的就是将其转换为相关的数据类型。

成功序列化类必须满足两个条件。

  • io.该类必须实现可序列化接口。
  • 类的所有字段都必须是可序列化的。如果甚至有一个字段不可序列化,则应将其标记为瞬态。

如果有人需要检查一个类是否可序列化,简单的解决方案是检查该类是否实现了 java.io.Serializing 方法;如果是,则它是可序列化的。如果不是,那就不是。人们应该注意到,将对象序列化到文件时,标准做法是为文件赋予 .ser 扩展名。

方法

如果类包含这些方法,它们将用于 Java 中的序列化。

1. Java中的序列化方法

Method Description
public final void writeObject (Object obj) throws IOException {} This will write the specified object to the ObjectOutputStream.
public void flush() throws IOException {} This will flush the current output stream.
public void close() throws IOException {} This will close the current output stream.

2. Java中反序列化的方法

Method Description
public final Object readObject() throws IOException, ClassNotFoundException{} This will read an object from the input stream.
public void close() throws IOException {} This will close ObjectInputStream.

Example of Serialization in Java

An example in Java is provided here to demonstrate how serialization works in Java. We created an Employee class to study some features, and the code is provided below. This employee class implements the Serializable interface.

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 letter to " + name + " " + address);
}
}

When this program finishes executing, it will create a file named employee.ser. This program does not provide a guaranteed output, rather it is for explanatory purposes only, and the objective is to understand its use and to work.

import java.io.*;
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Rahul Jain";
e.address = "epip, Bangalore";
e.SSN = 114433;
e.number = 131;
try {
FileOutputStream fileOut =
new FileOutputStream("https://cdn.educba.com/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}

The below-described DeserializeDemo program deserializes the above Employee object created in the Serialize Demo program.

import java.io.*;
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("https://cdn.educba.com/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 is 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);
}
}

Output:

Deserialized Employee…

Name: Rahul Jain

Address: epip, Bangalore

SSN: 0

Number:131

Some important points related to the program above are provided below:

  • The try/catch block above tries to catch a ClassNotFoundException. This is declared by the readObject() method.
  • A JVM can deserialize an object only if it finds the bytecode for the class.
  • If the JVM does not find a class during the deserialization, it will throw ClassNotFoundException.
  • The readObject () return value is always cast to an Employee reference.
  • When the object was serialized, the SSN field had an initial value of 114433, which was not sent to the output stream. Because of the same, the deserialized Employee SSN field object is 0.

Conclusion

Above, we introduced serialization concepts and provided examples. Let’s understand the need for serialization in our concluding remarks.

  • Communication: If two machines that are running the same code need to communicate, the easy way out is that one machine should build an object containing information that it would transmit and then serialize that object before sending it to the other machine. The method may not be perfect, but it accomplishes the task.
  • Persistence: If you want to store the state of an operation in a database, you first serialize it to a byte array and then store the byte array in the database for retrieval later.
  • Deep Copy: If creating a replica of an object is challenging and writing a specialized clone class is difficult, then the goal can be achieved by serializing the object and then de-serializing it into another object.
  • Cross JVM Synchronization: JVMs running on different machines and architectures can be synchronized.

以上是Java 中的序列化的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
上一篇:Java User Input下一篇:Applets in Java