Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should serialVersionUID be unique for different classes?

Tags:

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?

like image 488
Darshan Patel Avatar asked Jan 17 '14 09:01

Darshan Patel


People also ask

Can different classes have same serialVersionUID?

Yes, you can. Serial versions of different classes are independent and do not interfere each other. Eclipse even proposes you to set serialVersionID by default value that is 1L .

What should I set serialVersionUID to?

You should usually have the serialVersionUID as a private static final field in your class; you can choose any value. If you don't specify one, a value is generated automatically (this approach can lead to problems as it is compiler (object structure) dependent.

What is serialVersionUID what would happen if you don't define this?

The SerialVersionUID can be used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible w.r.t serialization. If the deserialization object is different than serialization, then it can throw an InvalidClassException.

What is a serialVersionUID and why should I use it?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization. Specifying one gives more control, though JVM does generate one if you don't specify.


1 Answers

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.

like image 78
Philip Voronov Avatar answered Oct 07 '22 00:10

Philip Voronov