Skip to content

@Nonnull fields are assumed to be non-null in the constructor #2713

Open
@Treeston

Description

@Treeston

Class fields annotated with @Nonnull are currently assumed to never be null in the class constructor.
@Nonnull only provides guarantees after construction has finished, and checking these fields in the constructor is often useful to avoid boilerplate variables.

A toy example illustrating the issue:

public class AnnotatedClass {
    private @Nonnull String specialValue;
    private @Nonnull Map<String, String> allValues = new HashMap<>();

    /* this constructor incorrectly warns that specialValue might not have been initialized */
    public AnnotatedClass(Iterable<String> values) {
        for (String entry : values)
        {
            String[] split = entry.split("=", 1);
            if (split.length != 2) throw new IllegalArgumentException("Value improperly formatted");

            final String key = split[0];
            final String value = split[1];
            if (value == null) /* needed to avoid warning on the assignment to specialValue later */
                continue;      /* side note: ideally we wouldn't need this, and the IDE           */
                               /*  would recognize that entry.split returns array of non-null     */
            this.allValues.put(key, value);
            if ("specialKey".equals(key))
                this.specialValue = value;
        }
        if (this.specialValue == null) /* the next line incorrectly produces a dead code warning */
            throw new IllegalArgumentException("The provided iterable does not have a special value!");
    }
}
Environment
  • Operating System: Windows 10 Enterprise
  • JDK version: openjdk 11.0.12 2021-07-20
  • Visual Studio Code version: 1.71.2
  • Java extension version: v1.11.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions