Why method name counts or generates a hash for serialversionuid

I have a class in the process of serializing

public class Name implements Serializable {
    private final String firstName;
    private final String lastName;

    public Name(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

      

But when de-serializing, I have an additional method (mentioned below) that doesn't affect the state of the object in any way, and serialization is all about saving the state of the object, and then why the additional method contributes to generating the hash for the serialversionuid. In the current scenario, it will fail with InvalidClassException. But the state of the object is not changed with this additional method.

public String getFullName() {
    return firstName + " " + lastName;
}

      

+3


source to share


2 answers


By default, you need to make sure that your serialized objects are only compatible if derived from the same class. For this, a number of class attributes are taken into account: https://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html#4100



In any case, if you are using serialization, you must define your own identifier.

+2


source


According to the documentation

For each non-private method, sorted by method name and signature:

The name of the method.
The modifiers of the method written as a 32-bit integer.
The descriptor of the method. 

      



The reason a public method is considered when serializing is because it looks like a contract. If a class has offered public methods that it supports, it shouldn't change over time. If this changes, the version of the class must be changed.

0


source







All Articles