June 29, 2022

Generate, Remove Getters and Setters in Eclipse IDE

Many a time I have seen especially freshers painstakingly writing get() and set() methods for each field in the class manually one by one. That is when IDEs do give the facility to generate get() and set() methods just by clicking a menu option. In this post we’ll see how to generate getters and setters in Eclipse IDE.

Generate getters and setters using Eclipse IDE

To generate get() and set() methods follow the following steps.

1. Create a class with fields that are required. For example suppose I have a Person class with fields firstName, lastName, age, gender so I’ll create the class with those fields only.

Java class with fields

2. Either press alt+shift+s,r from your keyboard or right click with in the class and choose source-generate getters and setters.

generate getters setters

3. Either way Eclipse opens a “generate getters and setters” window which allows you to generate getters and setters for selected fields. You can select all fields or the required fields. There are options to select if you only want getters or setters, access modifiers, insertion point (where in your class get() and set() methods should be written).

getter setter eclipse window

4. Click generate and your methods will be generated automatically. Now the Person class looks as given below.

public class Person {
  private String firstName;
  private String lastName;
  private int age;
  private char gender;
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public char getGender() {
    return gender;
  }
  public void setGender(char gender) {
    this.gender = gender;
  }
}

Removing field along with its getter and setter methods

If you want to remove a field along with its getters and setters, in Eclipse go to outline window select the field you want to delete – right click – choose delete option. Eclipse IDE asks you "Do you also want to delete getter/setter methods for field" choose yes to confirm deletion of getter and setter. That ensures removal of field along with its get() and set() methods.

delete getters setters eclipse

That's all for the topic Generate, Remove Getters and Setters in Eclipse IDE. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment