serialVersionUID가 없으면 잠재적 에러이다

Tags:

http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html

Interface 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.

Eclipse 3.1부터는 serialVersionUID가 java.io.Serializable을 구현한 클래스에 선언되어있지 않으면 에러를 내보낼 수 있게 되었습니다. 설명은 위에 본 바와같이 serialVersionUID 를 갖고 클래스를 식별하는데, 이를 사람이 안해주면 컴파일러 의존적인 UID가 나오게 된다. 따라서 다수의 compiler 라면 위험해질 수 있다 (즉 같은 클래스인데 serialize한게 deserialize안됨)는 겁니다. 그리고 컴파일러가 생성하면 느리기도 하구요.

아마 Effective JAVA에는 serialVersionUID에 대한 설명을 하면서 ‘속도 문제로 이걸 쓰자는 사람들이 있는데 말도 안된다’는 식으로 기술되있던 것 같은데 너무 설렁설렁봐서 기억이 잘 안나네요.

Comments

3 responses to “serialVersionUID가 없으면 잠재적 에러이다”

  1. 이석용 Avatar
    이석용

    맨날 구경만 하다가 글 올립니다.

    제가 지금 가진 Effective Java 책을 보니

    “기본 직렬화 형태를 쓰던 맞춤 직렬화 형태를 쓰던 직렬화를 제공하는 모든 클래스는 직렬 버전 고유식별자(Serival Version UID)를 명시적으로 제공하는 것이 좋다”

    라고 되어있네요.

  2. 민구 Avatar
    민구

    아.. 그렇군요.. 감사합니다 ^^

  3. JAVA에는 serialVersionUID에 대한 설명을 하면서 ‘속도 문제로 이걸 쓰자는 사람들이 있는데 말도 안된다’는 식으로 기술되있던 것 같은데 너무 설렁설렁봐서 기억이 잘 안나네요. 출처: http://mkseo.pe.kr/blog/?p=840

Leave a Reply

Your email address will not be published. Required fields are marked *