5

In my Java code I directly accessed some member variables. Now I want to refactor and use getter and setters. How can I make Eclipse automatically replace all direct assignments with setters and each access with a getter?

Right click -> Source -> Generate Getters and Setters just creates the functions but does not apply them in the rest of the code.

Jack Miller
  • 6,843
  • 3
  • 48
  • 66
  • Possible duplicate of http://stackoverflow.com/questions/3973204/eclipse-jdt-is-there-a-refactoring-to-replace-direct-field-accesses-with-setter – Jonn Apr 15 '14 at 13:13

1 Answers1

13

Use the Refactor menu. It has an item "encapsulate fields" which generates getters and setters just as "Source -> Generate Getters and Setters" does, but in addition it replaces all usages of the fields and makes the fields private.

(As a mnemonic: To change the structure of existing code (i.e. to refactor it), use the Refactor menu. To generate new code that is not used yet, use the Source menu. That is, if you create a new class with some getters and setters, you can use the help of the Source menu by coding the fields only and auto-generate the getters and setters afterwards. However if you want existing code to use getters and setters instead of direct field access, this is a classic case of code Refactoring.)

chiccodoro
  • 14,407
  • 19
  • 87
  • 130
  • Under the "Refactor" menu, I see an "Encapsulate Field..." menu item, but not an "Encapsulate Fields..." menu item. So if a class has many fields, the user is forced to repeatedly invoke "Encapsulate Field..." for each field. – JohnC Aug 16 '16 at 19:58
  • 1
    @JohnC - so it is. When you write a new class and the fields are not in use yet, you can use the "Generate Getters And Setters" option instead. For refactorings it is rather usual that only one thing is changed by one operation. – chiccodoro Aug 19 '16 at 10:47