其他分享
首页 > 其他分享> > Lombok中@Builder的使用

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

标签:String,weight,schoolName,grade,Builder,private,Student,使用,Lombok
来源: https://www.cnblogs.com/liftsail/p/16250182.html