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());
}
}

posted @ 2022-05-09 17:52  liftsail  阅读(133)  评论(0编辑  收藏  举报