Personally I would recommend Project Lombock for getter/setter generation.
It can also generate equals
, hashCode
and toString
.
It uses an annotation processor to generate the code at compile time so that it doesn't clutter up your classes.
So a simple class :
public class Example {
private String firstName;
private String lastName;
}
With getters,setters,equals and hashCode becomes:
public class Example {
private String firstName;
private String lastName;
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;
}
@Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + Objects.hashCode(this.firstName);
hash = 67 * hash + Objects.hashCode(this.lastName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Example other = (Example) obj;
if (!Objects.equals(this.firstName, other.firstName)) {
return false;
}
if (!Objects.equals(this.lastName, other.lastName)) {
return false;
}
return true;
}
}
Which is a right mess. With Lombock this can be done like so:
@Data
public class Example {
private String firstName;
private String lastName;
}
And if we decompile the compiled class we get:
public class Example {
public Example() {
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Example)) {
return false;
}
Example other = (Example) o;
if (!other.canEqual(this)) {
return false;
}
Object this$firstName = getFirstName();
Object other$firstName = other.getFirstName();
if (this$firstName != null ? !this$firstName.equals(other$firstName) : other$firstName != null) {
return false;
}
Object this$lastName = getLastName();
Object other$lastName = other.getLastName();
return this$lastName != null ? this$lastName.equals(other$lastName) : other$lastName == null;
}
public boolean canEqual(Object other) {
return other instanceof Example;
}
public int hashCode() {
int PRIME = 31;
int result = 1;
Object $firstName = getFirstName();
result = result * 31 + ($firstName != null ? $firstName.hashCode() : 0);
Object $lastName = getLastName();
result = result * 31 + ($lastName != null ? $lastName.hashCode() : 0);
return result;
}
public String toString() {
return (new StringBuilder()).append("Example(firstName=").append(getFirstName()).append(", lastName=").append(getLastName()).append(")").toString();
}
private String firstName;
private String lastName;
}
So all the code is there, including a toString
.