开发者

What is the difference of declaring private static final long serialVersionUID = xxxxxxxxL in classes that implements Serializable

What is the effect of declaring a private static final long serialVersionUID = 1945670924947820279L; in a class that implements Serializable?

I remember that one may implement the class without specifying the long, or开发者_开发百科 just 1L. What is the difference?

import java.io.Serializable;

public class KAS implements Serializable
{ 
    private static final long serialVersionUID = 1945670924947820279L;
}


If you do not specify a version, the JVM will use some internal rules to try to work out on its own whether or not the serialized object and the version in its own classloader are compatible. This can result in a situation where someone has an outdated jar but the deserialization still works, because the newer version of the class didn't change it in a way that is picked up as an incompatibility. (Perhaps you fixed a bug in a method implementation but left all the fields alone.)

Alternately you can exploit it by doing something like setting the value to 1 and never changing it if you want people with outdated versions to still be able to use the data.


If you want to safely deserialize/serialize instances, each version of the class needs a unique serialVersionUID. The deserialization process checks this value when deserializing - if it doesn't match an exception is thrown, preventing the serialized data from being deserialized into the wrong version of the class.

If you make the serialVersionUID always the same value, you might as well not have it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜