-
Notifications
You must be signed in to change notification settings - Fork 1.7k
INJECT_INNER_CLASS
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.
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() {
...
}
}
}
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
.
-
User's Guide
-
Integration
-
Extensions
-
Internals
-
Releases
-
Community