Search code examples
javajacksonrecorddto

How to convert constructor parameter in Java record?


I have DTO class and I need to replace it with record equivalent.

@Getter
@NoArgsConstructor
public class MyDTO {

    private Set<NotificationType> enabledSettings;

    @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
    public MyDTO(final Set<String> enabledSettings) {
        this.enabledSettings = enabledSettings.stream()
                .map(s -> NotificationType.valueOf(s.toUpperCase()))
                .collect(Collectors.toSet());
    }
}

The problem is that actually I receive Set<String> but getter should be for Set<NotificationType>. As for now I don't see any solution.


Solution

  • The problem is that the record encapsulates Set<NotificationType> and you would like to pass Set<String> to form the encapsulated field, but due to the type erasure, the constructor accepting Set<String> cannot be used.

    As long as you are not limited to Set, you can use a constructor with Collection<String>:

    public MyDTO(final Collection<String> enabledSettings) {
        this(enabledSettings.stream()
                .map(String::toUpperCase)
                .map(NotificationType::valueOf)
                .collect(Collectors.toSet()));
    }