2

Consider the below code. When I analyze the code for sonar rule, it complains about "javax.validation.constraints.NotNull" but is not initialized in this constructor.

I can resolve it by initializing the field with default value ( see example here ) but it will make @NotNull annotation redundant. So my question is how to resolve this problem in best possible way.

public class Dummy {

    @NotNull(message = "Dummy field cannot be null")
    private Integer dummyField;

    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 Answers1

6

You should move the @NotNull annotations to the constructor and setter parameters:

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

If you verify that all possible mutators of that value only set it to non-null values, it's the same effect as stating that the value itself must be non-null - but should avoid the spurious warning

Ben M
  • 1,833
  • 1
  • 15
  • 24