Serializable
인터페이스를 구현하면 직렬화 가능 클래스가 된다.Serializable
인터페이스는 아무것도 없는 빈 인터페이스다. 그냥 직렬화할 거라고 표시하기 위해 implement하는 것.static
, transient
필드는 직렬화에서 제외된다.hashCode
정의에 따라 같을 수도 있다.serialVersionUID
Serializable
인터페이스의 구현 객체를 컴파일 하면 자동으로 정적 필드 serialVersionUID
가 추가된다.serialVersionUID
가 달라진다.InvalidClassException
이 발생한다.public class XXX implements Serializable {
static final long serialVersionUID = LONG_VALUE;
}
{{JDK 설치 경로}}/bin/serialver.exe
는 자동으로 serialVersionUID
를 생성한다.Serializable
을 구현하고 있다면 super class 직렬화 시 sub class도 직렬화된다.Serializable
구현 여부와 무관하다.Serializable
을 구현하고 있다면 super class는 직렬화되지 않는다.이에 대한 방법은 다음의 두 가지가 있다.
1. super class가 Serializable
을 구현한다.
2. sub class에서 writeObject()
와 readObject()
를 선언해 직접 super class의 field를 출력한다.
private void writeObejct(ObjectOutputStream out) throws IOExceptino {
out.writeXXX(SUPER_CLASS_FIELD); // write fields of super object
...
out.defaultWriteObject(); //serialize fields of sub object
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
SUPER_CLASS_FIELD = in.readXXX(); // read fields of super object
...
in.defaultReadObject(); // deserialize fields of sub object
}
당연히 전자의 방법이 더 좋다.