@Data和@Getter与@Setter都是lombok插件的注解,用于简单对象的增强编译实现。
maven pom引入文件
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
源码参考:
@Getter
@Setter
public class Student {
public String name;
public int age;
}
编译后再反编译查看:
public class Student {
public String name;
public int age;
public Student() {
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
可以看到@Getter和@Setter仅对对象的属性进行了get set方法填充
源码:
@Data
public class Student {
public String name;
public int age;
}
编译后:
public class Student {
public String name;
public int age;
public Student() {
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Student)) {
return false;
} else {
Student other = (Student)o;
if (!other.canEqual(this)) {
return false;
} else {
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name == null) {
return this.getAge() == other.getAge();
}
} else if (this$name.equals(other$name)) {
return this.getAge() == other.getAge();
}
return false;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Student;
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $name = this.getName();
int result = result * 59 + ($name == null ? 43 : $name.hashCode());
result = result * 59 + this.getAge();
return result;
}
public String toString() {
return "Student(name=" + this.getName() + ", age=" + this.getAge() + ")";
}
}
可以看到@Data不仅包括了@Setter和@Getter的部分,还增强实现了toString hashCode canEqual equals
方法
http://blog.xqlee.com/article/2504011439221096.html