Understand NullAway's nullability model
masterNullAway operates on a 'non-null by default' assumption. It assumes every method parameter, return value, and field is non-null unless explicitly marked with a @Nullable annotation.
Workflow for fixing NPEs:
- Identify Error: NullAway reports an error when a
nullis passed to a parameter assumed to be@NonNull. - Annotate: Add
@Nullableto the parameter/field to acknowledge it can be null. - Check: NullAway will then flag any dereferencing of that
@Nullablevariable. - Guard: Add a null check (e.g.,
if (x != null)) to satisfy the checker.
// 1. Buggy code (assumes non-null)
static void log(Object x) {
System.out.println(x.toString());
}
static void foo() {
log(null); // Error: passing @Nullable parameter 'null' where @NonNull is required
}
// 2. Fixed with @Nullable and a null check
static void log(@Nullable Object x) {
if (x != null) {
System.out.println(x.toString());
}
}