Search code examples
javaexceptionstackuid

What is a serial version UID used for?


I'm creating a Java application, and when creating an interface to use with an ADT, it finds the need to initialize a random number as an ID number.

public class StackFullException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    public StackFullException(){}
    public StackFullException(String message) {
        super(message);
    }
}

I'm curious as to whether leaving this out will impact anything consequential about my program and if so, how to avoid it.


Solution

  • The serialVersionUID is part of the black magic of the Java serialization API.

    It is used to uniquely identify a version of the class so that when a class is de-serialized the version can be checked against the version of the class loaded by the ClassLoader.

    The serialization API will generate a serialVersionUID itself if none is specified but this is then subject to random change by inconsequential changes (or at least ones that don't break serialization compatibility).

    Adding the field yourself gives you control over this process - you decide when a change to the class should break de-serialization of older versions.

    More information can be found in the JavaDocs for Serializable.

    In short, if you plan to serialize this class and then de-serialize it later - but after making some changes to code and recompiling etc - this field is more-or-less essential to guarantee that this will work as intended.