Is there a way to automatically generate getters and setters in Eclipse?
Bring up the context menu (i.e. right click) in the source code window of the desired class. Then select the Source
submenu; from that menu selecting Generate Getters and Setters...
will cause a wizard window to appear.
Source -> Generate Getters and Setters...
Select the variables you wish to create getters and setters for and click OK
.
In Eclipse Juno, by default, ALT+SHIFT+S,R opens the getter/setter dialog box. Note you have to press all 4 keys.
All the other answers are just focus on the IDE level, these are not the most effective and elegant way to generate getters and setters. If you have tens of attributes, the relevant getters and setters methods will make your class code very verbose.
The best way I ever used to generate getters and setters automatically is using project lombok annotations in your java project, lombok.jar will generate getter and setter method when you compile java code.
You just focus on class attributes/variables naming and definition, lombok will do the rest. This is easy to maintain your code.
For example, if you want to add getter and setter method for age
variable, you just add two lombok annotations:
@Getter @Setter
public int age = 10;
This is equal to code like that:
private int age = 10;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
You can find more details about lombok here: Project Lombok
Right click -> Source -> Generate setters and getters
But to make it even more convenient, I always map this to ALT+SHIFT+G from Windows -> Preferences -> General -> Keys