@Data注解,主要做的工作如下
1、添加equals,CanEqual 方法,添加hashCode方法
2、添加toString方法
3、添加Set方法
4、添加Get方法
而上面的四件事,lombok中,有分别的注解去做,分别是 @EqualsAndHashCode、@ToString、@Setter、@Getter
所以,如果单纯为了添加Get、set 方法而使用data,会导致添加了1、2步骤中的冗余代码
这是使用Data注解的类
package com;
import lombok.Data;
@Data
public class Teacher {
private int id;
}
如果不加Data注解,编译之后的文件长这样
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com;
public class Teacher {
private int id;
public Teacher() {
}
}
加上Data注解之后,长下面这样
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com;
public class Teacher {
private int id;
public Teacher() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Teacher)) {
return false;
} else {
Teacher other = (Teacher)o;
if (!other.canEqual(this)) {
return false;
} else {
return this.getId() == other.getId();
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Teacher;
}
public int hashCode() {
int PRIME = true;
int result = 1;
int result = result * 59 + this.getId();
return result;
}
public String toString() {
return "Teacher(id=" + this.getId() + ")";
}
}
如果将@Data注解换成@Setter注解,编译之后的代码会变成下面这个样子
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com;
public class Teacher {
private int id;
public Teacher() {
}
public void setId(int id) {
this.id = id;
}
}
网友评论