serialVersionUID는 무엇이고 왜 사용하나요?

조회수 4565회

serialVersionUID를 정의하지 않으면 이클립스는 노란색 경고 메시지를 보여줍니다.

The serializable class Foo does not declare a static final serialVersionUID field of type long

serialVersionUID가 무엇인가요? 왜 중요한가요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    [java.io.Serializable] 자바 문서를 보면 원하시는 답이 잘 설명되어 있습니다.

    The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

    ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

    If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.

    객체를 스트림으로 변환하는 것을 객체의 직렬화라고 하고요. 반대로, 스트림을 객체로 변환하는 것을 객체의 역직렬화라고 합니다. 자바가상기계 (JVM)은 직렬화와 역직렬화를 하는 시점의 클래스에 대한 버전 번호를 부여합니다. 만약 그 시점에 클래스의 정의가 바뀌어 있다면 새로운 버전 번호를 할당합니다. 그래서 직렬화할 때의 버전 번호와 역직렬화를 할 때의 버전 번호가 다르면 역직렬화가 불가능하게 될 수도 있습니다. 이런 문제를 해결하려면 개발자가 직접 버전 번호를 정해주면 됩니다. 그것이 long 타입의 static final 필드인 serialVersionUID인 것이지요. 그 필드의 값을 정해주면 클래스의 정의가 변경되어도 직렬화/역직렬화가 가능합니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)