What does it mean: The serializable class does not declare a static final serialVersionUID field? [duplicate]
Asked Answered
C

5

249

I have the warning message given in the title. I would like to understand and remove it. I found already some answers on this question but I do not understand these answers because of an overload with technical terms. Is it possible to explain this issue with simple words?

P.S. I know what OOP is. I know what is object, class, method, field and instantiation.

P.P.S. If somebody needs my code it is here:

import java.awt.*;
import javax.swing.*;


public class HelloWorldSwing extends JFrame {

        JTextArea m_resultArea = new JTextArea(6, 30);

        //====================================================== constructor
        public HelloWorldSwing() {
            //... Set initial text, scrolling, and border.
            m_resultArea.setText("Enter more text to see scrollbars");
            JScrollPane scrollingArea = new JScrollPane(m_resultArea);
            scrollingArea.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));

            // Get the content pane, set layout, add to center
            Container content = this.getContentPane();
            content.setLayout(new BorderLayout());
            content.add(scrollingArea, BorderLayout.CENTER);
            this.pack();
        }

        public static void createAndViewJFrame() {
            JFrame win = new HelloWorldSwing();
            win.setTitle("TextAreaDemo");
            win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            win.setVisible(true);
        }

        //============================================================= main
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable(){
                public void run(){
                    createAndViewJFrame();
                }
            });
        }

}
Capello answered 18/2, 2010 at 13:40 Comment(3)
Can it be that the discussed warning message is a reason why my GUI application freeze?Capello
no, nothing to do with your gui freezing.Villanelle
Dup: #286293Skate
S
172

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:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

Stratfordonavon answered 18/2, 2010 at 13:41 Comment(4)
You can also let your IDE to autogenerate one.Forgat
@Forgat - how can we do that in eclipse ? Is it safe to auto generate ?Orchard
@JediKnight In Eclispse it is Window>Preferences>Java>Code Style>Clean Up>Missing Code>activate "Add serial version ID" under "Potential programming problems". Then if you are in the default profile, obviously you must save it as a different one.Didynamous
Don't auto generate serialVersionUID when you are not using serialization. This already happens during compilation, without having to poison your source code with a stupid random number just to keep your IDE happy. Just turn off the Eclipse warning, because that's where the actual confusion comes from. If you ever do want to use serialization (likelyhood of that is approaching 0 these days), then read up about it, and use the serialVersionUID as a VERSION NUMBER (starting at 1, and incremented when your class definition changes with special code to read older versions).Motivity
P
46

The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.

Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).

If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial").

If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.

Piliform answered 26/4, 2013 at 16:36 Comment(4)
There are several major mistakes in your citation, and also some self-contradictions.Chromatophore
@EJP It would be helpful for all if you enumerated the errors.Piliform
@EJP It just occurred to me that there are two citations in my answer. To which citation are you referring?Piliform
I am referring to the Javaworld article, but the only citations in your answer are to third-party resources, which don't have any more standing than answers on this website: often considerably less so. The only relevant citations are the normative references: the JLS, the JVM Specification, the Java Object Serializatikn Specification, and the Javadoc.Chromatophore
B
37

The reasons for warning are documented here, and the simple fixes are to turn off the warning or put the following declaration in your code to supply the version UID. The actual value is not relevant, start with 999 if you like, but changing it when you make incompatible changes to the class is.

public class HelloWorldSwing extends JFrame {

        JTextArea m_resultArea = new JTextArea(6, 30);
        private static final long serialVersionUID = 1L;
Blepharitis answered 18/2, 2010 at 14:19 Comment(1)
The reasons for the warning are documented in the Java Object Serialization Specification and the Javadoc. StackOverflow answers are not normative references.Chromatophore
C
27

it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)

That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(), and/or readResolve() or /writeReplace() methods and/or a serializableFields declaration that could cope with the change.

Chromatophore answered 18/2, 2010 at 21:16 Comment(0)
A
5

Any class that can be serialized (i.e. implements Serializable) should declare that UID and it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...). The field's value is checked during deserialization and if the value of the serialized object does not equal the value of the class in the current VM, an exception is thrown.

Note that this value is special in that it is serialized with the object even though it is static, for the reasons described above.

Alie answered 18/2, 2010 at 13:42 Comment(4)
I JFrame a serializable class? What is UID and how I can declare it? Does my code "changes something that affects the serialization"? What actually the serialization means?Capello
Yes, JFrame is a java.awt.Component which implements Serializable. Code never changes anything that affects serialization, only programmers do that. I don't know a list that lists all changes that affect serialization. Check en.wikipedia.org/wiki/Serialization#Java for a description of serialization in Java.Cordiality
It is not serialized with the object. It shouldn't be changed unless you want to break compatibility, or if you have already done so by departing from what it says in the Versioning section of the specification. That does not include adding or reordering fields. The correct reference is not Wikipedia but the Object Serialization Specification.Chromatophore
"additional fields, removed fields, change of field order" don't matter at all. Only type changes matter if you don't implement readObject() to handle the change.Satanism

© 2022 - 2024 — McMap. All rights reserved.