Guice injecting a generic list

I would like to inject a list of various objects which differentiate with their generic type.

I have a MainView who accepts a list of ContentPanels (a subtype of Jpanel) which I want to display.

So i have

@Inject
MainView(List<ContentPanel<?>> contentPanel){
   ...
}

the content panels differ in their generic type, so there is one for books, one for a movie etc.

I tried to bind them with

bind(new TypeLiteral<AbstractContentPanel<Book>>(){})
        .to(new TypeLiteral<BookContentPanel<Book>>(){})
        .in(Singleton.class);

and

bind(new TypeLiteral<AbstractContentPanel<Movie>>(){})
            .to(new TypeLiteral<BookContentPanel<Movie>>(){})
            .in(Singleton.class);

but how can I make a list of them and inject them into my MainView?

Upvotes: 0

Views: 1477

Answers (1)

Vladimir Matveev
Vladimir Matveev

Reputation: 127781

If you want to inject all your bindings into a list, then you cannot do that. If you want to inject a list, you should bind it directly, like this:

bind(new TypeLiteral<List<String>>() {})
  .toInstance(new ArrayList<String>());

But in this case your list must be known beforehand (or supplied via a Provider).

If you want to access your bindings through a sequence, you'll have to use multibinding extension. In that case your code could look like this:

Multibinder<ContentPanel<?>> multibinder = Multibinder.newSetBinder(binder(), new TypeLiteral<ContentPanel<?>>() {});
multibinder.addBinding().to(YourContentPanelImpl1.class);
multibinder.addBinding().to(YourContentPanelImpl2.class);
// and so on

And then you can inject a Set:

@Inject
MainView(Set<ContentPanel<?>> contents) {
    ...
}

Upvotes: 4

Related Questions