Friday, August 7, 2009

eclipse magic part 1: automatically generate getters and setters for your instance variables

Everyone who tried to write a getter / setter (accessor, mutator) method for more than 2-3 fields knows that it's a pain. Eclipse can automatically generate a getter/setter method for the instance variable you choose. Assume that I have a java bean for a student (StudentBean).


public class StudentBean {
private int studentId;
private String name;
private float gpa;
}


If I'm going to write a get/set method for each variable I'll have to write 6 methods in total. Let Eclipse to this job.
 Source > Generate Getters and Setters


Then choose the fields.



You can choose the insertion point of the automatically generated methods, their order and their access modifiers. My new StudentBean is now like this:


public class StudentBean {

private int studentId;
private String name;
private float gpa;

public int getStudentId() {
return studentId;
}

public String getName() {
return name;
}

public float getGpa() {
return gpa;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public void setName(String name) {
this.name = name;
}

public void setGpa(float gpa) {
this.gpa = gpa;
}

}

3 comments:

  1. is there any short cut key to generate getters and setters for the properties

    ReplyDelete
  2. there's no shortcut key by default but you can easily define one.
    go to window > preferences > general > keys.
    then write "getter" in the textbox.
    choose "generate getters setters" and click on binding. then choose the key combination you'd like for this task.

    ReplyDelete