>  기사  >  Java  >  Java의 직렬화

Java의 직렬화

王林
王林원래의
2024-08-30 16:06:52789검색

Java의 직렬화는 객체의 상태를 바이트 스트림으로 변환하는 메커니즘입니다. 역직렬화는 반대 프로세스입니다. 역직렬화를 통해 실제 Java 객체가 바이트 스트림의 메모리에 생성됩니다. 이러한 메커니즘은 개체에 지속됩니다. 이렇게 직렬화를 통해 생성된 바이트 스트림은 어떤 플랫폼에도 의존하지 않습니다. 다른 플랫폼에서는 문제 없이 한 플랫폼에서 직렬화된 객체를 역직렬화할 수 있습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

따라서 직렬화 및 역직렬화의 전체 프로세스는 JVM에 독립적입니다. 클래스 객체를 직렬화하려면 java.io.Serialized 인터페이스를 구현해야 합니다. Java에서 직렬화 가능한 것은 마커 인터페이스입니다. 구현할 필드나 메서드가 없습니다. 이 프로세스는 옵트인(Opt-In) 프로세스와 유사하게 클래스를 직렬화할 수 있게 만듭니다.

Java의 직렬화는 ObjectInputStream과 ObjectOutputStream 두 클래스에 의해 구현됩니다. 필요한 것은 파일에 저장하거나 네트워크를 통해 전송할 수 있도록 래퍼를 두는 것뿐입니다.

Java의 직렬화 개념

위 섹션에서 언급한 직렬화 클래스인 ObjectOutputStream 클래스에는 다양한 데이터 유형을 작성하기 위한 여러 작성 메소드가 포함되어 있지만 가장 널리 사용되는 메소드는 하나입니다.

public final void writeObject( Object x ) throws IOException

위 방법을 사용하여 객체를 직렬화할 수 있습니다. 이 메서드는 또한 이를 출력 스트림으로 보냅니다. 마찬가지로 ObjectInputStream 클래스에는 객체 역직렬화를 위한 메소드가 포함되어 있습니다.

public final Object readObject() throws IOException, ClassNotFoundException

역직렬화 방법은 스트림에서 객체를 검색하고 이를 역직렬화합니다. 반환 값은 다시 객체이므로 관련 데이터 유형으로 캐스팅하기만 하면 됩니다.

클래스의 성공적인 연재를 위해서는 두 가지 조건이 충족되어야 합니다.

  • 아이오. 클래스는 직렬화 가능한 인터페이스를 구현해야 합니다.
  • 클래스의 모든 필드는 직렬화 가능해야 합니다. 하나의 필드라도 직렬화할 수 없으면 임시로 표시해야 합니다.

클래스가 직렬화 가능한지 확인해야 하는 경우 간단한 해결책은 클래스가 java.io.Serialized 메서드를 구현하는지 확인하는 것입니다. 그렇다면 직렬화 가능합니다. 그렇지 않다면 그렇지 않습니다. 객체를 파일로 직렬화할 때 표준 관행은 파일에 .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 사용자 입력다음 기사:Java 사용자 입력