Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse JDT: Is there a refactoring to replace direct field accesses with setter/getter methods?

Tags:

I know I can generate setters and getters for fields in the Eclipse source menu, but I'm very surprised it doesn't offer to replace the direct field accessors with calls to the newly created methods.

Does anyone know how to do this short of manual search and replace?

Thanks!

like image 422
Jeff Axelrod Avatar asked Oct 19 '10 22:10

Jeff Axelrod


People also ask

Can Eclipse generate getters and setters?

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.

How do I change my getters and setters in Eclipse?

Select "Javadoc -> Generate Getter/Setter Javadocs from Field Javadocs..." in the main menu of Eclipse or the context menu of the editor, and a dialog opens. The shortcut key is Ctrl+Shift+D. In the dialog select getters and setters for which you want to generate Javadocs and click "OK" button.

What is another commonly used name for getter and setter methods?

Given this, getters and setters are also known as accessors and mutators, respectively. The getter method returns the value of the attribute.

Can we use getter without setter?

If your class is going to be used in the environment where setter is not required (e.g. ORM / dependency injection / serialization frameworks), it should be OK to do not use setter. In this particular case setter does not make much sense since variable is final and set only once.


1 Answers

There is a way. Focus on the attribute, right click. Select "Refactor" -> "Encapsulate Field".

(Edited to explain why it works, even though the menu's title doesn't imply it)

The "Encapsulate Field" dialog-box will create getters/setters for you if they don't exist, and will change field-access to go through the getters/setters. The dialog automatically detects existing getters/setters so, for the requirements that you had mentioned, that would do the trick.

like image 196
Isaac Avatar answered Sep 25 '22 05:09

Isaac