Open
Description
openedon Oct 3, 2022
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment