Stop Writing Getters, Setters and Constructors in Java

A Fancy Tool to Cut Down Boilerplate Code in Java

Shafi Rizvi
Javarevisited

--

Photo by Nadine Shaabana on Unsplash

Java is considered as a verbose language by some developers. That is, repetitive code are written in the application making the code unclean and difficult to read at times. Getters, setters, constructors, hashCode(), equals(), toString() are few of the most regularly used boilerplate code in java.

Take a look at the following code.

public class Student{

private String firstName;
private String lastName;
private int age;
public class Student(){
}

public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// getters and setters - around 20 to 25 lines of code// hashCode(), equals(), toString() - another 20 or more lines of
// code
}

If we look at the above Student class, with just three fields it consumes around 45 to 50 lines of code for getters, setters, constructors, hashCode(), equals() and toString() methods. What if I say that there is a way to eliminate all those lines of code and replace it with just a few annotations. Doesn’t it sound great? True that…

--

--