Skip to content

INJECT_INNER_CLASS

Googler edited this page Aug 12, 2020 · 1 revision

INJECT_INNER_CLASS

Summary

Guice can automatically inject concrete types using just-in-time(JIT) bindings. However, inner classes can not be injected because they have an implicit reference to the enclosing class which Guice doesn't know how to create. See nested class documentation.

Example:

final class Foo {
  class Bar {
    @Inject
    Bar() {
      ...
    }
  }
}

final class FooModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(Foo.Bar.class);
  }
}

Guice will throw an INJECT_INNER_CLASS error when FooModule is used.

Common Causes

Missing static modifier

Sometimes a class is mistakenly defined as a non-static inner class, and in those cases the fix for this error is simply marking the inner class as static:

final class Foo {
  static class Bar {
    @Inject
    Bar() {
      ...
    }
  }
}

Using inner class as an just-in-time binding

If the inner class can not be static then you must provide an explicit binding for the class and not rely on just-in-time bindings.

For example, use a custom @Provides method instead:

final class Foo {
  class Bar {
    Bar() {
      ...
    }
  }

  Bar createBar() {
    // This instance of Bar will have an implicit reference
    // to this particular Foo instance.
    return new Bar();
  }
}

final class FooModule extends AbstractModule {
  @Provides
  Bar provideBar(Foo foo) {
    return foo.createBar();
  }
}

The above fix assumes that there is a binding for Foo.

Clone this wiki locally