Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "declare a static final serialVersionUID" warning mean and how to fix? [duplicate]

Tags:

java

Possible Duplicate:
What does it mean: The serializable class does not declare a static final serialVersionUID field?

Java compiler warning: The serializable class [*****] does not declare a static final serialVersionUID field of type long.

Why? How to fix it?

like image 505
user496949 Avatar asked Apr 12 '11 07:04

user496949


People also ask

What does serialVersionUID mean?

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 serialVersionUID and why do we need 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.

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 the purpose of serialVersionUID in Java?

Simply put, we use the serialVersionUID attribute to remember versions of a Serializable class to verify that a loaded class and the serialized object are compatible. The serialVersionUID attributes of different classes are independent. Therefore, it is not necessary for different classes to have unique values.


1 Answers

This is explained fairly well 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.

You fix the error by adding

private static final long serialVersionUID = 7526472295622776147L;  // unique id

to the class.

Further reading:

  • java.io.Serializable
  • Why should I bother about serialVersionUID? (stackoverflow)

A side note: If you're using Eclipse and if you (and no one else) ever plan to serialize your classes, you can also suppress the error by going to

     Window → Preferences → Java → Compiler → Errors/Warnings

and select "Ignore" on "Serializable Class without serialVersionUID".

like image 74
aioobe Avatar answered Sep 16 '22 17:09

aioobe