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.
CodePudding user response:
I would suggest to create a static factory method:
public record MyDTO(Set<NotificationType> enabledSettings) {
public static MyDTO create(final Set<String> enabledSettings) {
return new MyDTO(enabledSettings.stream()
.map(s -> NotificationType.valueOf(s.toUpperCase()))
.collect(Collectors.toSet()));
}
}
CodePudding user response:
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()));
}
CodePudding user response:
//**@Getter
@NoArgsConstructor
public class MyDTO {
private Set<NotificationType> enabled settings;
@JsonCreator(mode=JsonCreator.Mode.PROPERTIES)
public MyDTO(final Set<String>enabledSettings) {
this.enabledSettings=enabledSettings.stream().maps-> NotificationType.valueOf(s.toUpperCase())).collect(Collectors.toSet());
}
}
//You should try once.(factory method)
public record MyDTO(Set<NotificationType> enabledSettings) {
public static MyDTO create(final Set<String> enabledSettings) {
return new MyDTO(enabledSettings.stream()
.map(sk -> NotificationType.valueOf(sk.toUpperCase()))
.collect(Collectors.toSet()));
}
}