목차

Java Serialization 직렬화

Serializable 하지 않은 필드가 중간에 껴 있다면

@Test
@DisplayName("serialize : ")
void serialize() throws IOException, ClassNotFoundException {
 
 
    Person person = new Person("나야나", new Age(41));
    System.out.println("직접 생성 객체 : " + person);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        try ( ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(person);
        }
 
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) {
            final Person deserializedPerson = (Person) ois.readObject();
            System.out.println("역직렬화 객체 : " + deserializedPerson);
        }
    }
}
 
@AllArgsConstructor
@Getter
@Setter
@ToString
public static class Person implements Serializable {
    private String name;
    private Age age;
}
 
 
@AllArgsConstructor
@Getter
@Setter
@ToString
public static class Age {
    private int age;
}

결과

serialtest.SerializationTest$Age
java.io.NotSerializableException: serialtest.SerializationTest$Age
	at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)

serialVersionUID 읽기