Skip to content

NULL_INJECTED_INTO_NON_NULLABLE

Googler edited this page Oct 7, 2020 · 5 revisions

NULL_INJECTED_INTO_NON_NULLABLE

Summary

Guice will throw NULL_INJECTED_INTO_NON_NULLABLE error when null is injected into a non-nullable injection point.

Example:

final class Foo {
  @Inject
  Foo(Bar bar) {
    // If Guice does not enforce bar to be non-null, then the next line will
    // throw NullPointerException when bar is null. If bar is passed down
    // somewhere else, the eventual exception might be hard to trace so it's
    // better to fail early.
    bar.doSomething();
  }
}

final class BarModule extends AbstractModule {
  @Provides
  Bar provideBar(Baz baz) {
    return baz.getBar(); // Baz.getBar may return null
  }
}

The above example will cause NULL_INJECTED_INTO_NON_NULLABLE error when provideBar returns null for Bar.

Common Causes

Unexpected null value

If the binding is not expected to be null then make sure that wherever the binding is provided does not return null.

Example:

final class BarModule extends AbstractModule {
  @Provides
  Bar provideBar(Baz baz) {
    // Baz.getBar may return null, so handle it here by returning a default
    // instance of Bar when baz.getBar returned null
    Bar bar = baz.getBar();
    if (bar == null) {
      return new Bar("some default value");
    } else {
      return bar;
    }
  }
}

Parameter or field was not marked as @Nullable

If null is a valid value for a binding, mark the parameter or field as explicitly @Nullable and handle the possible null value.

Examples:

import javax.annotation.Nullable;

final class Foo {
  private final Optional<Bar> optionalBar;

  @Inject
  Foo(@Nullable Bar bar) {
    // Handle the possible null value here
    this.optionalBar = Optional.fromNullable(bar);
  }
}

See Use @Nullable for more information.

Note: In Kotlin, you can instead change Bar to Bar?.

Using the wrong @Nullable annotation

If you've annotated the parameter as @Nullable but are still getting the NULL_INJECTED_INTO_NON_NULLABLE error, then make sure you are using a @Nullable annotation that Guice supports.

Clone this wiki locally