Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What means 1L serialVersionUID? When could I use this default value 1L?

Tags:

There are 3 ways to define the serialVersionUID :

1. private static final long serialVersionUID = 1L; (Default)
2. private static final long serialVersionUID = -8940196742313994740L; (Generated)
3. Don't define serialVersionUID and let the JVM define it at runtime. @Lance Java

But I don't understand the first way!

I have seen it already, that somebody defines "serialVersionUID=1L" for all java-classes in source code.

What is the meaning? Is that useful?

If all classes have the same serialVersionUID 1L, is there no problem?

like image 734
Ying Style Avatar asked Feb 18 '14 10:02

Ying Style


2 Answers

What is the meaning? Is that useful?

Yes. The point of serialVersionUID is to give the programmer control over which versions of a class are considered incompatible in regard to serialization. As long as the serialVersionUID stays the same, the serialization mechanism will make a best effort to translate serialized instances, which may not be what you want. If you make a semantic change that renders older versions incompatible, you can change the serialVersionUID to make deserializing older instances fail.

If all classes have the same serialVersionUID 1L, is there no problem?

No - the serialVersionUID is per class.

like image 157
Michael Borgwardt Avatar answered Sep 23 '22 19:09

Michael Borgwardt


This is explain here:

The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.


From the javadoc:

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:


Useful Links

  1. java.io.Serializable
  2. Why should I bother about serialVersionUID? (StackOverflow)
  3. serialVersionUID in Java Serialization
like image 37
ravibagul91 Avatar answered Sep 22 '22 19:09

ravibagul91