如何为嵌套的java类创建构造函数/生成器?

41zrol4v  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(371)

假设我想用以下结构模拟一个类,用于测试目的:

@Data
public class Street() {

    private House house;

    @Data
    static class House {
        private List<Room> rooms;
    }

    @Data
    static class Room {
        private Door door;
    }

    @Data
    static class Door {
        private String material;
    }
}

简洁地创建一个 Street 对象,包含 House 有一个 Room 有木门吗?
我在考虑加一个Lombok山 @Builder 注解到 Street 类,但我发现每个嵌套类也需要构建器,我想知道是否有更干净的方法来实现这一点。

y0u0uwnf

y0u0uwnf1#

我唯一的建议是:

public class Street {

    private House house;
    private Room room;
    private Door door;

    public class House{
        //build class House
    }

    public class Room{
        //build class Room
    }

    public class Door{
        //build class Door
    }

    public Street(House house, Room room, Door door) {
        this.house = new House();
        this.room = new Room();
        this.door = new Door(); 
    }

}

然后,您可以在street类中使用必须访问嵌套到street中的其他小类的方法的对象

hfsqlsce

hfsqlsce2#

使用lombok项目的@superbuilder
假设你有:

@Getter
@SuperBuilder
public class Parent {
    private final String parentName;
    private final int parentAge;
}

@Getter
@SuperBuilder
public class Child extends Parent {
    private final String childName;
    private final int childAge;
}

@Getter
@SuperBuilder
public class Student extends Child {
    private final String schoolName;
}

然后你可以创建这样一个新学生:

Student student = Student.builder()
  .parentName("Andrea")
  .parentAge(38)
  .childName("Emma")
  .childAge(6)
  .schoolName("Baeldung High School")
  .build();

参考文献:https://www.baeldung.com/lombok-builder-inheritance#lombok-生成器和继承-1

相关问题