就我个人而言,我会推荐Project Lombock用于 getter/setter 生成。
它还可以生成equals
和。hashCode
toString
它使用注释处理器在编译时生成代码,这样它就不会弄乱你的类。
所以一个简单的类:
public class Example {
private String firstName;
private String lastName;
}
使用 getter、setter、equals 和 hashCode 变为:
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;
}
}
这是一个正确的混乱。使用 Lombock 可以这样做:
@Data
public class Example {
private String firstName;
private String lastName;
}
如果我们反编译编译后的类,我们会得到:
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;
}
所以所有的代码都在那里,包括toString
.