Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two different setters for an field using lombok

Tags:

java

lombok

I am using @Setter to generate setter but I also want to add one more setter for same field with different datatype as input.

@Setter
private Date date;

It will generate:

public void setDate(Date date) {
  this.date = date;
}

I also want to add one more setter where input is of format String.

public void setDate(String date) {
  this.date = Date.valueOf(date);
}

By using @Setter and adding setDate(String date) setter, lombok is not able to auto generate setDate(Date date) setter. Is there way I can auto generate setter using Date as input and add one more setter explicitly accepting String as input.

like image 367
user3505394 Avatar asked Sep 19 '25 12:09

user3505394


1 Answers

From the doc:

No method is generated if any method already exists with the same name (case insensitive) and same parameter count. For example, getFoo() will not be generated if there's already a method getFoo(String... x) even though it is technically possible to make the method. This caveat exists to prevent confusion. If the generation of a method is skipped for this reason, a warning is emitted instead. Varargs count as 0 to N parameters. You can mark any method with @lombok.experimental.Tolerate to hide them from lombok.

My suggestion is to use something like (or use the experimental annotation):

@Setter
private Date date;

public void setDateFromString(String date) {
  this.date = Date.valueOf(date);
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!