3

I have a class while serialization

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 while de-serializing I have an extra method(mentioned below) that is not affecting object state in any way and serialization is all about storing the object state then why an extra method is having contribution in the hash generation for serialversionuid. In current scenario it will fail with InvalidClassException. But object state is not getting changed by this extra method.

public String getFullName() {
    return firstName + " " + lastName;
}
Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59
  • Good question, but that's just how it is, unfortunately. It seemed to me even in 1997 that it hadn't been thought through sufficiently at the time. The solution as always is to provide your own `serialVersionUID.` – user207421 Oct 26 '14 at 08:30
  • Thanks EJB, seems it was not done deliberately , I am not able to find any significance of this. – user1678270 Oct 26 '14 at 09:26

2 Answers2

2

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

In any case, if you use serialization, you should define your own id.

mrks
  • 8,033
  • 1
  • 33
  • 62
0

As per 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 in serializing is because it is like a contract. If a class has suggested the public methods that it supports, It should not change with time. If this changes, the version of the class must be changed.

Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59