Lombok(1.14.8) - @Getter, @Setter, @ToString, @EqualsAndHashCode & @Data

时间:2023-01-24 15:08:56

@Getter / @Setter

@Getter 和 @Setter,分别实现了 Gette r和 Setter 方法。

package com.huey.hello.bean;

import java.util.Date;

import lombok.Getter;
import lombok.Setter; public class Student { @Getter @Setter
private int studNo;
@Getter @Setter
private String studName;
@Getter @Setter
private Date birthday; public static void main(String[] args) {
Student stud = new Student();
stud.setStudName("huey");
System.out.println(stud.getStudName()); // [OUTPUT]: huey
}
}

@ToString

@ToString,实现了 toString() 方法。

package com.huey.hello.bean;

import java.util.Date;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString; @ToString
public class Student { @Getter @Setter
private int studNo;
@Getter @Setter
private String studName;
@Getter @Setter
private Date birthday; public static void main(String[] args) {
Student stud = new Student();
stud.setStudNo(10001);
stud.setStudName("huey");
stud.setBirthday(new Date());
System.out.println(stud); // [OUTPUT]: Student(studNo=10001, studName=huey, birthday=Fri Jul 31 23:01:56 CST 2015)
}
}

@EqualsAndHashCode

@EqualsAndHashCode,实现了 equals() 和 hashCode() 方法。

package com.huey.hello.bean;

import java.util.Date;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter; @EqualsAndHashCode
public class Student { @Getter @Setter
private int studNo;
@Getter @Setter
private String studName;
@Getter @Setter
private Date birthday; public static void main(String[] args) {
Student stud1 = new Student();
stud1.setStudNo(10001);
stud1.setStudName("huey");
stud1.setBirthday(new Date()); Student stud2 = new Student();
stud2.setStudNo(10001);
stud2.setStudName("huey");
stud2.setBirthday(new Date()); System.out.println(stud1.hashCode()); // [OUTPUT]: -349449895
System.out.println(stud2.hashCode()); // [OUTPUT]: -349449895
System.out.println(stud1.equals(stud2)); // [OUTPUT]: true
}
}

@Data

@Data,相当上述三个 annotation 以及 @RequiredArgsConstructor。

package com.huey.hello.bean;

import java.util.Date;

import lombok.Data;

@Data
public class Student { private int studNo;
private String studName;
private Date birthday; public static void main(String[] args) {
Student stud1 = new Student();
stud1.setStudNo(10001);
stud1.setStudName("huey");
stud1.setBirthday(new Date()); Student stud2 = new Student();
stud2.setStudNo(10001);
stud2.setStudName("huey");
stud2.setBirthday(new Date()); System.out.println(stud1.hashCode()); // [OUTPUT]: -349006373
System.out.println(stud2.hashCode()); // [OUTPUT]: -349006373
System.out.println(stud1.equals(stud2)); // [OUTPUT]: true
System.out.println(stud1); // [OUTPUT]: Student(studNo=10001, studName=huey, birthday=Fri Jul 31 23:13:43 CST 2015)
}
}