简体   繁体   中英

Should serialVersionUID be unique for different classes?

class A implements Serializable{
    private static final long serialVersionUID = 5L;
    ...
}

and

class B implements Serializable{
    private static final long serialVersionUID = 6L;
    ...
}

then it is necessary to give unique serialVersionUID to both classes.

So can I assign serialVersionUID = 5L for both classes?

I read following links

Why generate long serialVersionUID instead of a simple 1L?

What is a serialVersionUID and why should I use it?

Yes, you can. Serial versions of different classes are independent and do not interfere each other.

PS
Eclipse even proposes you to set serialVersionID by default value that is 1L .

serialVersionUID is needed to remember versions of the class. It should be same while serializing and deserializing. It is a good programming practice to provide this value rather than JVM assigning one(generally it is hash). It is not necessary for two classes to have unique values.

serialVersionUID can be anything.

But the best practice is to start with the lowest number (for example 0L ) and update it whenever you make a change in class which affects serialization , for example, adding/updating/removing a field, in which case you should increase the version number from 0L to 1L and so on.

SerialVersionUUID is an identifier used by a compiler to serialize/deserialize an object. This id is a private member to the class.

Creating new uuid for every serializable is good to have control over the serialization/deserialization process but it need NOT be unique among different classes.

是的,两个不同的类可能具有相同的serialVersionUID变量。但是更喜欢为每个类使用唯一的一个。还要使用8到10位数的长度而不是1作为值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM