본문 바로가기

자바

자바 Serializeble

1.Serializeble 이란?

   - 인터페이스로서, 객체를 직렬화 할 수 있도록 지원하는 기능이다.

 

2. 직렬화란 ? 

   - 객체를 바이트 형태로 변환하여 파일 저장이나 네트워크 전송을 할 때 사용한다.

   - jvm의 메모리에 있는 객체 데이터를 바이트 형태로 변환하는 기술을 의미한다.

   - 클래스가 파일을 읽거나 쓸 수 있도록 하거나, 다른 서버로 보내거나 받을 때 반드시 사용해야한다.

 

3. 역직렬화란 ?

   - 반대로 직렬화된 바이트 데이터를 다시 원래의 객체로 변환하는 과정이다.

 

4. 직렬화 / 역직렬화 예시 코드

import java.io.*;

// 직렬화를 위해 Serializable 인터페이스를 구현
class Person implements Serializable {
    private static final long serialVersionUID = 1L; // 직렬화 버전 UID (옵션)
    private String name;
    private int age;

    // 생성자
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter, Setter (생략)
    // ...

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        // 객체 생성
        Person person = new Person("John", 30);

        // 객체를 직렬화하여 파일에 저장
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            oos.writeObject(person);
            System.out.println("Serialization complete.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 파일에서 직렬화된 객체를 읽어와 역직렬화
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person deserializedPerson = (Person) ois.readObject();
            System.out.println("Deserialization complete.");
            System.out.println("Deserialized Person: " + deserializedPerson);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Person 클래스는 Serializable 인터페이스를 구현한다.

main 메서드에서는 Person 객체를 생성한 후, ObjectOutputStream을 사용하여 해당 객체를 직렬화하여 "person.ser" 파일에 저장한다.

그리고 ObjectInputStream을 사용하여 "person.ser" 파일에서 직렬화된 객체를 읽어와 역직렬화를 수행하고, 역직렬화된 객체를 출력한다.

 

5. transient 예약어

   - transient 예약어는 객체를 저장하거나, 다른 JVM으로 보낼 때 직렬화 대상에서 제외된다.

private transient int age;

 

'자바' 카테고리의 다른 글

자바 UDP통신  (0) 2023.07.29
자바 Socket  (0) 2023.07.29
자바 NIO ( Non-blocking I/O )  (0) 2023.07.28
자바 I/O  (0) 2023.07.25
자바 Quick Sort  (0) 2023.07.25