处理null值等 - 在构建器类范例中?

时间:2017-11-08 17:59:57

标签: java builder

我有一个自定义类型的构建器类...并且我并不总是确定是否存在值。

所以我要说我这样做:

MyCustomObject customObj = new MyCustomObject.MyCustomObjectBuilder()
    .setValueA(valueA)
    .setValueB(valueB)
    .setValueC(valueC)
    .setValueD(valueD)
    .setValueE(valueE)
    .build();

如果我的值为null,那么这显然会中断,但我觉得这个代码块中有单独的空检查,否定了可重用的构建器类的可读性和便利性......有没有办法处理这个?

1 个答案:

答案 0 :(得分:1)

setValueX()方法被调用为MyCustomObjectBuilder的实例方法 因此,即使您提供null作为参数,也无关紧要 因为这些方法中的每一个都必须返回this作为最后一个语句 这是建设者的工作方式。

例如:

public class MyCustomObject {

    private MyCustomObject(){}
    ...
    public static class MyCustomObjectBuilder {

       public MyCustomObjectBuilder setValueA(A a){
          ... // do assignment or anything

           // at the end
          return this;
       }

       public MyCustomObjectBuilder setValueB(B b){
          ... // do assignment or anything

           // at the end
          return this;
       }
       ...
    }
}

当然,如果在setValueX()方法内部,您引用参数的成员,则首先要检查它是否为null