我有一个PivotModel
课程,我将使用new
关键字进行初始化。
PivotModel pivotModel = new PivotModel()
当初始化pivotModel
时,所有依赖字段(model1,model2,cell1,cell2)应该使用新对象初始化但不能为null。
我想在不使用新构造函数的情况下初始化依赖类的所有字段和字段。我不想要样板代码。
如果您有任何标准做法,请在此处发布。我也在我的项目中使用lombok
。
public class PivotModel {
@Getter
@Setter
private Model1 model1;
@Getter
@Setter
private Model2 model2;
private Model3 model3 = new Model3() -----> Dont want to initialise this way for these fields
}
public class Model1 {
private Map<String,Cell> cell1;
private Map<String,Cell> cell2;
private Map<String,Cell> cell3;
------ will have some 10 fields here
}
答案 0 :(得分:3)
您似乎在java项目中使用Lombok项目,您可以在类上方添加@Getter @Setter
Scope,Lombok还提供Constructor Annotation,因此只需在类上方键入范围@AllArgsConstructor
所以你上课应该是这样的
@Getter
@Setter
@AllArgsConstructor
public class PivotModel {
private Model1 model1;
private Model2 model2;
}
@Getter
@Setter
@AllArgsConstructor
public class Model1 {
private Map<String,Cell> cell1;
private Map<String,Cell> cell2;
private Map<String,Cell> cell3;
}
答案 1 :(得分:2)
对于初始化,我建议使用 Builder Pattern 。
//keep your initialization logic in builder class and use build()/create() wherever required. Let's say:
Class Pivot{
// Note: this have only getters for members
//inner builder class
PivotModelBuilder{
//Note: all setter will be part of builder class
/**
* method which return instantiated required object.
*/
public PivotModel build(){
return new PivotModel(this);
}
}
}
//access initilization code as:
PivotModel pivot = new Pivot.PivotModelBuilder().build()
添加引荐链接:https://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html (您可以搜索有关构建器模式及其在线实现的更多信息)
限制: