본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

JAVA

직렬화가 가능한 클래스 Serializable의 transient 직렬화 제외

직렬화 가능한 클래스를 만들기 위해서는 `Serializable` 인터페이스를 구현해야 한다.
https://standout.tistory.com/1507

 

직렬화란? 데이터 저장, 네트워크 데이터 통신

직렬화 데이터 저장, 네트워크 데이터 통신 데이터나 객체를 일련의 바이트로 변환하는 프로세스 데이터를 파일에 저장하거나 네트워크를 통해 전송할수 있게 한다. Java에서는 Serializable 인터페

standout.tistory.com

https://standout.tistory.com/1508

 

Serializable 인터페이스 직렬화 ObjectOutputStream, 역직렬화 ObjectInputStream와 각 메서드: 인터페이스 구

Serializable 인터페이스 자바에서 직렬화를 수행한다. https://standout.tistory.com/1507 직렬화란? 데이터 저장, 네트워크 데이터 통신 직렬화 데이터 저장, 네트워크 데이터 통신 데이터나 객체를 일련의

standout.tistory.com

 

 

transient
직렬화하지 않고 싶은 필드가 있다면 `transient` 키워드를 사용하여 해당 필드를 지정할 수 있다.
아래의 예시코드에서 `name` 필드는 직렬화되지만 
`age` 필드는 `transient`로 지정되어 직렬화 과정에서 제외된다.

class Person implements Serializable {
    private static final long serialVersionUID = 1L; // 직렬화 버전 UID
    private String name;
    private transient int age; // 직렬화에서 제외할 필드

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}
직렬화된 객체를 파일로 저장하고 다시 읽어들이는 예시 코드

public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 30);

        // 객체를 파일에 저장 (직렬화)
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            out.writeObject(person);
            System.out.println("직렬화된 객체를 파일에 저장했습니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 파일에서 객체를 읽어들임 (역직렬화)
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person restoredPerson = (Person) in.readObject();
            System.out.println("파일에서 역직렬화된 객체를 읽어왔습니다:");
            System.out.println(restoredPerson);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

[출력결과]
직렬화된 객체를 파일에 저장했습니다.
파일에서 역직렬화된 객체를 읽어왔습니다:
Person{name='John', age=30}