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!
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.
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.
Given this, getters and setters are also known as accessors and mutators, respectively. The getter method returns the value of the attribute.
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.
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.
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