Search code examples
javaguice

Get a wildcard instance from Google Guice


Hi I am experimenting with Google Guice 5.x. I have my class defined as:

public class Foo<T> {
    // some logic here
}

and it's being used in other classes like:

public class Bar {

    private final Foo<Chocolate> provider;

    public Bar(Foo<Chocolate> _choco) {
        this.provider = _choco;
    }
}


public abstract class BaseZoo { // in some other package in a different jar

    private final Injector injector = Guice.createInjector(new MyAppModule());

    private Foo<?> provider;

    public String doSomething() {

        if (provider == null)
            this.provider = this.injector.getInstance(Foo.class);

        // some other code logic.
    } 
}

Now, in my module file (MyAppModule) I have defined Foo as:

@Inject
@Provides
@Singleton
public Foo<Chocolate> getFoo(FooDependency fooDep) {
    return new Foo<>(fooDep);
}

Now when I run my code, Google Guice is able to find an instance for Foo<Chocolate> but is not able to find an instance for Foo<?>.

Is there a way to configure Google Guice to resolve Foo<?> with an instance of Foo<Chocolate>?


Solution

  • Bind the type:

    @Inject
    @Provides
    @Singleton
    public Foo<?> getFoo(FooDependency fooDep) { ... }
    

    If you still want to bind Foo<Chocolate>, use the @Provides method in the question, but also bind Foo<?> to it, you can do so in your configure method:

    bind(new Key<Foo<?>>() {}).to(new Key<Foo<Chocolate>>() {});
    

    or, with a provider method:

    @Provides
    Foo<?> provideWildcardFoo(Foo<Chocolate> chocolateFoo) {
      return chocolateFoo;
    }