// 직렬화 예시
public class User implements Serializable {
private String name;
private int age;
}
// 객체 → 바이트 스트림 (직렬화) [ implements Serializable이 수행하는 내용 ]
User user = new User("John", 30);
byte[] bytes;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(user);
bytes = bos.toByteArray();
}
// 바이트 스트림 → 객체 (역직렬화)
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis)) {
User deserializedUser = (User) ois.readObject();
}
JSON, Protocol Buffers 등의 대체 직렬화 방식 선호
성능과 유연성이 더 좋은 대안들 사용
Java 직렬화는 레거시 시스템이나 특수한 경우에 사용