Is there a way to automatically generate getters and setters in Eclipse?

I am working on a new Android project (Java), and created an Object with a large number of variables. Since I am planning to add getters and setters for all of them, I was wondering: is there a shortcut in Eclipse for automatically generating the getters and setters in a given class?


Solution 1:

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.

Solution 2:

In Eclipse Juno, by default, ALT+SHIFT+S,R opens the getter/setter dialog box. Note you have to press all 4 keys.

Solution 3:

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

Solution 4:

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

Solution 5:

Ways to Generate Getters & Setters -

1) Press Alt+Shift+S, then R
2) Right click -> Source -> Generate Getters & Setters
3) Go to Source menu -> Generate Getters & Setters
4) Go to Windows menu -> Preferences -> General -> Keys (Write Generate Getters & Setters on text field)
5) Click on error bulb of the field -> create getters & setters ...
6) Press Ctrl+3 and write getters & setters on text field then select option Generate Getters & Setters

if Mac OS press Alt+cmd+S then select Getters & Setters