1

Consider the below code:

class TestSUid implements Serializable {

    private static final Long serialVersionUID =101010101010L; 
    private String title;
    private Error error;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Error getError() {
        return error;
    }

    public void setError(Error error) {
        this.error = error;
    }
}

class Error implements Serializable {
    private String title;
    private String message;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Now my objective is to serialize the TestSUid class so that I can enable offline caching. I am confused on the part if I need to add a serialVersionUID to my Error class as well. What if I need to update the error class in future would updating the TestSUid version id be enough?

I have gone through the reference at: https://docs.oracle.com/javase/8/docs/platform/serialization/spec/version.html#a6678

But still dont feel entirely confident.

1 Answer 1

1

The reference you pointed to, lists compatible and incompatible changes when the class serialVersionUID is the same. So if you want to make any compatible change in the future (e.g. add a field to the class) and still be able to deserialize the old data, you should also add the serialVersionUID to the class that will change (in this case, also to the Error class). Additionally:

  1. As per Serializable javadoc you should use the primitive type long instead of a class Long.
  2. If you update the TestSUid version id, you will no longer be able to read the serialized data of an older version. You will get an exception: java.io.InvalidClassException: TestSUid; local class incompatible: stream classdesc serialVersionUID = <old_version>, local class serialVersionUID = <new_version>.
  3. If you don't update the TestSUid version id and add an additional field to the Error class, the computed (if not declared) serialVersionUID will be different than before and you will get the error from pt. 2.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.