4

If I have a class like this:

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;
    }
}

Will its calculated serialVersionUID change if I add another method (and no additional fields)?

For example, adding the method:

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

Alternatively, is there a nice tool for figuring this out?

Pete Doyle
  • 937
  • 7
  • 11

3 Answers3

8

Yes, it will change the serialVersionUID.

You can use the serialver command line tool - at least in Sun's JDK to calculate the serialVersionUID for a given compiled class.

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278
  • Thanks for the quick response! I was just able to use the serialver tool to verify this. Before: serialVersionUID = 7949745139928005557L. After: serialVersionUID = 7699267648627402486L. – Pete Doyle Jun 15 '09 at 23:33
  • 1
    The UID may also differ depending on which Java compiler is used. – Esko Luontola Jun 15 '09 at 23:49
  • Of course, if you choose the right method name, you can get back the same UID. – Tom Hawtin - tackline Jun 16 '09 at 00:07
  • @Tom Hawtin - tackline : care to provide an example? – Robert Munteanu Jun 16 '09 at 06:22
  • If the serial UID differs depending on what compiler you use, I think you have a bug. Part of the point of serialization is that you can serialize on one platform and deserialize on another. – DaBlick Jun 20 '13 at 20:02
  • It's worth noting that just because serialVer outputs a different serialVersionUID doesn't mean you would need to change it if you're handling this yourself. For example, even though adding a static method would change the generated serialVersionUID, that's not really necessary, as an extra static method won't change how the data is serialized.. so there won't be serialization errors if serialVersionUID doesn't change in code. – Alkanshel Sep 22 '16 at 19:13
1

Yes, it will change. An easy way is Eclipse: If the class implements Serializable and you do not provide a serialVersionUID field, the IDE displays a warning symbol. You can click on the warning sign and select "Add generated serial version UID". This will calculate a serialVersionUID for you and insert it in your code.

boxofrats
  • 882
  • 6
  • 8
0

When I started testing my beans it seemed to me that the serialVersionUID was regenerated when the class was compiled, not only when its signature changed. The reason for that could be the maven build and the fact that the old class was deleted before the new build.

Ravi Wallau
  • 10,416
  • 2
  • 25
  • 34