Lombok中@Builder的使用

没有继承的情况

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

有继承的情况

  1. 对于父类,使用@AllArgsConstructor注解
  2. 对于子类,手动编写全参数构造器,内部调用父类全参数构造器,在子类全参数构造器上使用@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());
    }
}

参考博客

[1]https://blog.csdn.net/lqadam/article/details/82719841
[2]https://cloud.tencent.com/developer/article/1419097
常用的几种注解
[3]https://blog.csdn.net/u014803081/article/details/84574016
[4]https://www.jianshu.com/p/63038c7c515a

你可能感兴趣的:(Java,EE)