I'd like to have my setters so that I can chain them like:
myPojo.setX(x).setY(y);
Usually I generate setters with Eclipse but unfortunately code template
for setters allows me to change only the body of the setter, not the signature.
What would be the easiest way to complete the above? Besides search-and-replace + manual editing? :)
To generate getters and setters, do the following: Create the fields you want in the class then press Alt+Shift+S, R. A dialog will pop up allowing you to choose the fields you want to generate getters and setters for. Click Select All to create getters/setters for all fields.
Setter returns nothing (undef) One of the possibilities is that the setter will return "nothing". As there is no real "nothing" in Perl, this means the function needs to return undef.
Setters cannot return values. While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.
I can offer a kind of patch that however does not require any additional installations.
Go to Window/preferences/Java/Code Style/Code templates. Edit "setter body" template as following:
${field} = ${param}; return this;
Now when you run "generate getters and setters" it will create setter like:
public void setMyField(String myField) { this.myField = myField; return this; }
This obviously cause compilation error because the method type is void
. But you can strike Ctrl-F
and replace all 'public void set' by public YourClassName set
.
It is a patch, but it works...
You could use the Editor/Templates for this purpose. To define a new Template open the Preferences Window, then Java->Editor->Templates. In this window you can define a new template and give it a name. For example:
public ${enclosing_type} setName(${argType} name) { this.name = name; return this; }
Give it a name, e.g. settr. You can then use this template in your java code by typing 'settr' and then Ctrl-Space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With