Reputation: 299
I have a class that looks like this:
@EqualsAndHashCode
@RequiredArgsConstructor
public class StatusUpdate {
@Getter
@Setter
private Long id;
@Getter
@Setter
@NonNull
private String text;
@Getter
@Setter
@NonNull
private Date added;
}
And I want to create these two constructors using Lombok:
public StatusUpdate(String text) {
this.text = text;
}
public StatusUpdate(String text, Date added) {
this.text = text;
this.added = added;
}
I tried using all three annotations: @NoArgsConstructor @RequiredArgsConstructor @AllArgsConstructor
But I couldn't do that with these, I only have one constructor that has two parameters, so I need one more constructor with one parameter only. I read this topic: @SomeArgsConstructor and this is what I need but since this does not exists I guess I should create manually one arg constructor that I need and other constructors I'll handle with Lombok, or is there any better / more elegant way to do it using Lombok only?
Thanks!
Upvotes: 6
Views: 11053
Reputation: 1852
use @Builder
annotation with your entity class and build your object manually.
User user = User.builder()
.username(signupDto.getUsername())
.email(signupDto.getEmail())
.password(encoder.encode(signupDto.getPassword()))
.roles(roles)
.build();
Upvotes: 0
Reputation: 9537
Yeah, you should just add them yourself. Years ago there was already a discussion to add the @SomeArgsConstructor
annotation, but since the Lombok team never did add that annotation, I think it is unlikely they will ever do it.
Or, as stated in the comments, use the builder pattern with the @Builder annotation. Then you could write something like: StatusUpdate.builder().text("text").date(new Date()).build();
.
Btw, if you do annotate all your fields with @Getter
, @Setter
and use the @EqualsAndHashCode
and @RequiredArgsConstructor
on class level, I think the @Data annotation could be a good fit for this class.
Upvotes: 5