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

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에 대한 설명을 하면서 ‘속도 문제로 이걸 쓰자는 사람들이 있는데 말도 안된다’는 식으로 기술되있던 것 같은데 너무 설렁설렁봐서 기억이 잘 안나네요.

Similar Posts:

Comments 2