Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload lombok setter

Tags:

java

lombok

We can use lombok to generate setter like this:

@Data                    //or @Setter
public class Test {  
    int a;
}

Say for instance I also want an overloaded setter that would take a String:

public void setA(String aStr){
    //parseInt and set 'a'
}

But when I add this overloaded method, lombok thinks that I have manually added a setter and so it chooses not to add one itself.

Apparently it looks only at the method name and not the parameters.

Is there a way I can force it to add the normal (that takes an int as parameter) setter?
Or the only way is to add that normal setter myself (using IDE setter generator of course)? I have a lot of fields and a lot of classes.

like image 778
Kartik Avatar asked Oct 15 '19 06:10

Kartik


2 Answers

Adding the @Tolerate annotation on my overloaded method solved the issue.

Documentation:

Put on any method or constructor to make lombok pretend it doesn't exist, i.e., to generate a method which would otherwise be skipped due to possible conflicts.

It has been experimental though, since 2014.

like image 172
Kartik Avatar answered Sep 22 '22 01:09

Kartik


The documentation states that "No method is generated if any method already exists with the same name (case insensitive) and same parameter count.".

This is the case that you've described. Instead, you should define an additional custom setter method with a new name like

setAFromString(String aStr)

like image 34
robingood Avatar answered Sep 26 '22 01:09

robingood