1

I have the following Object

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

public class SomeObject {
    @Valid
    @NotNull
    private int someCount;

    public int getSomeCount() {
        return someCount;
    }

    public void setSomeCount(final int someCount) {
        this.someCount = someCount;
    }

    public SomeObject(final int someCount) {
        this.someCount = someCount;
    }
}

But I get

"someCount" is marked "javax.validation.constraints.NotNull" but is not initialized in this constructor.

and it's pointing to the constructor. I'm passing an item into the constructor. How do I fix this

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • you don't need the `@Valid` annotation. also, you can probably resolve the problem by explicitly declaring the default no-arg constructor and assigning it a bogus value e.g. `-1`. – mre Jan 20 '18 at 03:30

2 Answers2

2

You are having a primitive type int here. It can't be null. Rather I would suggest you using @Min(0) validator instead. If you really need to have null passed in as a value then use a wrapper Integer instead. For that you can have a null check as above. I don't recommend this approach though.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
0

"javax.validation.constraints.NotNull" but is not initialized in this constructor

We have recently encountered this issue in our sonar build.

To fix this issue we initialized the non-null field at the time of deceleration itself.

Consider below code.

public class Dummy {

    @NotNull(message = "Dummy field cannot be null")
    private Integer dummyField = -1; // Any default value


    public Dummy(Integer dummyField) {
        this.dummyField = dummyField;
    }

    public Integer getDummyField() {
        return dummyField;
    }

    public void setDummyField(Integer dummyField) {
        this.dummyField = dummyField;
    }


}
Shahid
  • 481
  • 1
  • 8
  • 22
  • 1
    If it can't be null, why should you annotate it with `@NotNull`? – Clijsters Aug 08 '18 at 13:00
  • Actually you are correct Clijsters. SonarQube didn't like if you annotate the field Notnull and you don't initialize it. So in order to make the code compliance with Sonar quality, I can add a default value at the time of deceleration. However it will make Notnull annotation redundant – Shahid Aug 08 '18 at 15:24