Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate setters that return self in Eclipse

Tags:

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? :)

like image 735
vertti Avatar asked Sep 06 '12 07:09

vertti


People also ask

Can generate getters and setters in Eclipse?

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.

What is the return type for a setter method?

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.

Can a setter return a value in Java?

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.


2 Answers

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...

like image 60
AlexR Avatar answered Sep 28 '22 07:09

AlexR


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.

like image 24
paweloque Avatar answered Sep 28 '22 08:09

paweloque