Lombok中@Builder的使用
1.沒有繼承的情況
@Data
@Builder
public class Student {
private String schoolName;
private String grade;
public static void main(String[] args) {
Student student = Student.builder().schoolName("清華附小").grade("二年級").build();
// Student(schoolName=清華附小, grade=二年級)
System.out.println(student);
}
}
2.有繼承的情況
對於父類,使用@AllArgsConstructor註解
對於子類,手動編寫全引數構造器,內部呼叫父類全引數構造器,在子類全引數構造器上使用@Builder註解
@Data
@AllArgsConstructor
public class Person {
private int weight;
private int height;
}
@Data
@ToString(callSuper = true)
public class Student extends Person {
private String schoolName;
private String grade;
@Builder
public Student(int weight, int height, String schoolName, String grade) {
super(weight, height);
this.schoolName = schoolName;
this.grade = grade;
}
public static void main(String[] args) {
Student student = Student.builder().schoolName("清華附小").grade("二年級")
.weight(10).height(10).build();
// Student(super=Person(weight=10, height=10), schoolName=清華附小, grade=二年級)
System.out.println(student.toString());
}
}