java-14serialversionuidjava-record

does serialVersionUID make sense in a java record?


Does it make sense to add a serialVersionUID field to a record? I think a record might be meant to be serializable, so implementing Serializable and adding a serialVersionUID might be unnecessary, but I don't know.

public record JwtAuthenticationRequest(String username, String password) implements Serializable {

    @Serial
    private static final long serialVersionUID = -5867678037406733770L;
}

Is there anything special about records that I should know in the context of serialization and is it still a good practice to add serialVersionUID in records like in normal classes?


Solution

  • No unless you think you might change the record into a class in the future and you also don't like that the record's serialVersionUID will be 0.

    Notice that there is no need to add any additional boilerplate to RangeRecord in order to make it serializable. Specifically, there is no need to add a serialVersionUID field, since the serialVersionUID of a record class is 0L unless explicitly declared, and the requirement for matching the serialVersionUID value is waived for record classes.

    Changing a class from a record class to an ordinary class - A record class that relies on default serialization, may be changed to an ordinary class. The ordinary class must declare an explicit serialVersionUID, whose value is the same as that of the prior record class's serialVersionUID, or 0L if the prior record class does not have an explicit serialVersionUID declaration. The name and type of the ordinary class's serializable fields must match that of the name and type of the prior record class's components.