2

Hello is there a possibility to pass all nulls to constructor and have correctly new object created?

Lets say I have such class:

public class MobileDataReportSearchCriteria extends BaseSearchCriteria<MobileDataReport> {
    private Date reportDateFrom;
    private Date reportDateTo;
    private long opponentStationId;
    private boolean correctness;

    public MobileDataReportSearchCriteria() {
    }

public MobileDataReportSearchCriteria(Date reportDateFrom, Date reportDateTo, long opponentStationId, boolean correctness) {
    this.reportDateFrom = reportDateFrom;
    this.reportDateTo = reportDateTo;
    this.opponentStationId = opponentStationId;
    this.correctness = correctness;
}
}

and now I want to instantiate new object of this class with new MobileDataReportSearchCriteria(null, null, null, null); because those objects in business logic could be nulls. How to do that because when I do that I get NullPointerException. Thank you in advance!

Qbi
  • 445
  • 4
  • 13
  • 1
    One possibility: `this.reportDateFrom = Optional.ofNullable(reportDateFrom).orElseGet();` – Turing85 Jun 05 '21 at 11:32
  • 2
    You should use Long opponentStationId, Boolean correctness i.e. wrapper classes to allow null values instead of primitive types i.e. long, int, boolean etc – maneesh54321 Jun 05 '21 at 11:43
  • 1
    Related: [Can an int be null in Java?](https://stackoverflow.com/questions/2254435/can-an-int-be-null-in-java) – Ole V.V. Jun 05 '21 at 12:14
  • 1
    @Turing85 I think not. Am I or are you reading the question wrong?? – Ole V.V. Jun 05 '21 at 12:16
  • 1
    @OleV.V. I don't know. For me, it sounded like OP wants to check for `null` values on the parameters and assign the parameter's value to the corresponding field if the parameter iis not `null` and the default value the corresponding parameter is `null`. – Turing85 Jun 05 '21 at 12:18

0 Answers0