javaserialization

Should I do Java record class implement Serialization?


I did DTO object cache. Error occurred code.

public record EventListCopyResponse(
        Long eventCode,
        String title,
        String content,
        String image,
        String thumbnail,
        String link,
        MemberRole role,
        LocalDateTime createdAt,
        LocalDateTime updatedAt
) {
}

@Override
@Cacheable("event")
public List<EventListCopyResponse> execute(MemberRole role) {
    List<Event> events = loadEventService.findAllByMemberRole(role);
    return eventMapper.toEventListResponse(events);
}

Error occurred this code.

java.io.InvalidClassException: com.api.presentation.information.event.model.response.EventListCopyResponse; class invalid for deserialization

So, I did record class implements Serialization

public record EventListCopyResponse(
        Long eventCode,
        String title,
        String content,
        String image,
        String thumbnail,
        String link,
        MemberRole role,
        LocalDateTime createdAt,
        LocalDateTime updatedAt
) implements Serializable {
}

Then it works.

As far as I know, a Java record class already implements Serializable, so why does it have to be implemented explicitly for it to work?


Solution

  • Your assumption is wrong, a record class does not implement serializable by default, so adding it explicitly is the correct thing to do in this case.

    JEP 395: Records only says the following about serialization, and that is to establish that like normal classes they can be serialized, and the limitations (no customization of serialization/deserialization):

    Instances of record classes can be serialized and deserialized. However, the process cannot be customized by providing writeObject, readObject, readObjectNoData, writeExternal, or readExternal methods. The components of a record class govern serialization, while the canonical constructor of a record class governs deserialization.

    This doesn't mean they are serializable by default. Just like normal Java classes, you need to explicitly add implements Serializable to actually make them serializable.