如果构造函数的值为null,我可以给它一个默认值吗?

时间:2018-07-26 14:49:30

标签: java android constructor

我正在使用回收站视图在我的应用程序上显示数据。当我想从我正在使用的API中获取信息时,我要使用14个不同的变量。

for(int i = 0; i<array.length();i++){
    JSONObject object = array.getJSONObject(i);

    //object.getJSONObject("test");

    Personnel personnel = new Personnel(

            object.getInt("contactType"),
            object.getString("currentTime"),
            object.getString("clockIn"),
            object.getString("clockOut"),
            object.getInt("isClockedIn"),
            object.getString("clockInPhotoName"),
            object.getDouble("clockInLat"),
            object.getDouble("clockInLng"),
            object.getDouble("clockOutLat"),
            object.getDouble("clockOutLng"),
            object.getDouble("projectSiteLat"),
            object.getDouble("projectSiteLng"),
            object.getDouble("clockInDistanceFromProjectSiteInMetres"),
            object.getDouble("clockOutDistanceFromProjectSiteInMetres")
    );

    personnelList.add(personnel);
}

但是在我的http调用的响应正文中,例如,有时调用“ isClockedIn”的对象可能为空,如果执行此操作,则构造函数将不会创建对象。

这是我很长的构造函数:

public Personnel(int contactType, String totalTimeSummary, String clockInTime, String clockOutTime, int isClockedIn, String clockInPhotoName, double clockInLat, double clockInLong, double clockOutLat, double clockOutLong, double projectLat, double projectLong, double clockInDistance, double clockOutDistance) {
    this.contactType = contactType;
    this.totalTimeSummary = totalTimeSummary;
    this.clockInTime = clockInTime;
    this.clockOutTime = clockOutTime;
    this.isClockedIn = isClockedIn;
    this.clockInPhotoName = clockInPhotoName;
    this.clockInLat = clockInLat;
    this.clockInLong = clockInLong;
    this.clockOutLat = clockOutLat;
    this.clockOutLong = clockOutLong;
    this.projectLat = projectLat;
    this.projectLong = projectLong;
    this.clockInDistance = clockInDistance;
    this.clockOutDistance = clockOutDistance;
}

我环顾四周,发现如果我的其他构造函数没有填写所有需要的变量,则可以只创建一个默认的构造函数,但是我当然不想这样做,因为那样的话,所有参数都将为空。 / p>

干杯。

3 个答案:

答案 0 :(得分:1)

您可以使用optDouble代替调用getDouble。第一个值应该是您已经在使用的密钥,第二个值应该是在服务器响应中找不到该密钥时将使用的值。

您可以在此处找到一些真实的示例:https://www.programcreek.com/java-api-examples/?class=org.json.JSONObject&method=optDouble

答案 1 :(得分:0)

您不应使用原始变量。例如,int不能为null,另一方面,整数类型可以为null。看看这个link

答案 2 :(得分:-1)

正如GhostCat建议的那样,您应该真正考虑构建器模式,例如:

public Personnel {
    public static class Builder {
        int contactType;
        //all the other members

        public Builder contactType(int contactType) {
            this.contactType = contactType;
            return this;
        }

        public Personnel build() {
            Personnel personnel = new Personnel();
            personnel.contactType = this.contactType;
        }
    }


    int contactType;
    //all the other members

    private Personnel() {}

    // getters and setters

}

Personnel personnel = new Personnel.Builder()
    .contactType(0)
    .build();
相关问题