@NotNull annotated field and constructor

Good day, everybody!

Please, look at this code:

public class Property {
    @NotNull
    private
String name;   // <- warning "Not-null fields must be initialized"

    public
Property(@NotNull final String name) {
        setName(name);     
    }

    public void setName(@NotNull final String name) throws InvalidValueException {
        if (name.isEmpty())
            throw new InvalidValueException("Property name shouldn't be empty");
        this
.name = name;
    
}
}

public class Property {
    @NotNull
    private
String name;    // <- No warnings, all OK

    public
Property(@NotNull final String name) {
        this.name = name;
    
}
}


Could anybody explain, why I have NotNull warning if I initialize the field using method with guaranteed not-null parameter? What is the right way to implement this functionality?
Thank you in advance.

2 comments
Comment actions Permalink

IDEA uses similar semantics for @NotNull fields as it uses for final fields. So it should be able to statically prove that the field is initialized with a non-null value during object construction. It doesn't analyze method calls. Furthermore, in this particular case that couldn't have been done at all because setName is overrideable and there's no guarantee that possible overriders will initialize name.

For this case, I'd extract the non-emptiness check to a method and write something like this "this.name = checkName(name)". setName would use the same checkName inside. Otherwise you can suppress the inspection for this field (Alt+Enter on the warning and press Right) or disable "Not-null fields must be initialized" check in inspection settings.

0
Comment actions Permalink

Peter, thank you for your competent and irrefragable answer!
Good luck and Happy New Year!

0

Please sign in to leave a comment.