전체 코드는
class User {
String name;
String nickname;
}
class AirUser extends User implements Serializable {
int age;
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeUTF(name);
out.writeUTF(password);
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
name = in.readUTF();
password = in.readUTF();
in.defaultReadObject();
}
}
Serializable 코드를 보면 아무 것도 없는데 writeObject(), readObject()는 어디에서 누가 호출을 해서 사용을 할까?
public interface Serializable {
}
자바에서 private void writeObject(ObjectOutputStream out) throws IOException {} 메서드는 오버라이딩(override)이 아닌데도 갑자기 호출되는 것처럼 보일 수 있습니다.
이 메서드는 자바의 직렬화(Serialization) 과정에서 특별한 역할을 합니다.
Serializable 인터페이스를 구현한 클래스에서 직렬화 동작을 커스터마이즈하고 싶을 때 사용하는 특수 메서드입니다.private void writeObject(ObjectOutputStream out) throws IOException이어야 하며, 접근 제어자가 반드시 private 이어야 자동으로 호출됩니다.ObjectOutputStream.writeObject()를 호출할 때, 해당 객체에 이 특수한 private writeObject 메서드가 있으면 자동으로 실행됩니다.private writeObject를 가질 수 있습니다.