-
Notifications
You must be signed in to change notification settings - Fork 1.7k
UseNullable
To eliminate NullPointerExceptions in your codebase, you must be disciplined
about null references. We've been successful at this by following and enforcing
a simple rule:
Every parameter is non-null unless explicitly specified.
The
Guava: Google Core Libraries for Java
and JSR-305 have simple APIs to get a
nulls under control. Preconditions.checkNotNull can be used to fast-fail if a
null reference is found, and @Nullable can be used to annotate a parameter
that permits the null value:
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;
public class Person {
...
public Person(String firstName, String lastName, @Nullable Phone phone) {
this.firstName = checkNotNull(firstName, "firstName");
this.lastName = checkNotNull(lastName, "lastName");
this.phone = phone;
}Guice will refuse to inject null and throw a ProvisionException with
NULL_INJECTED_INTO_NON_NULLABLE
error instead. If null is permissible by your class, you can annotate the
field or parameter with @Nullable.
Due to an oversight, Guice allowed null to be injected into
@Provides methods in the
past. When this oversight was fixed, an option to control the enforcement level
was added to avoid breaking existing code:
-
IGNORE:nullis allowed to be injected into@Providesmethods -
WARN: a warning is logged whennullis injected into a@Proviesmethod -
ERROR: an error is thrown when whennullis injected into a@Providesmethod
ERROR level enforcement is recommended so that:
- Guice consistently rejects
nullunless@Nullableis used -
NullPointerExceptions are caught early by Guice in all types of injections
Guice by default uses ERROR so you don't need to do anything to configure
this. However, if for some reason that you need to relax this enforcement level,
you can do so by setting the JVM property
"-Dguice_check_nullable_provides_params" to either WARN or IGNORE.
Guice recognizes any @Nullable annotation that targets ElementType.PARAMETER
(for parameters) or ElementType.FIELD (for fields), like
edu.umd.cs.findbugs.annotations.Nullable or javax.annotation.Nullable.
Annotations like org.checkerframework.checker.nullness.qual.Nullable that
target TYPE_USE and/or TYPE_PARAMETER will not work because those are not
returned by the methods that Guice uses to get the annotations at runtime for
the nullability checks. So make sure that you are importing the correct
@Nullable when marking a parameter or a field as @Nullable in Guice.
-
User's Guide
-
Integration
-
Extensions
-
Internals
-
Releases
-
Community