Hierarchical lookup

63 views
Skip to first unread message

Mariano Gonzalez

unread,
Jun 5, 2018, 5:57:09 PM6/5/18
to google-guice
Hello,

I want to perform a hierarchical lookup. Suppose I have the following code:

bind(Apple.class).in(Singleton.class);
bind
(Banana.class).in(Singleton.class);
bind
(Grape.class).in(Singleton.class);

Now suppose that Apple and Grape implement the JuiceFactory interface, which Banana does not.

How do I programmatically lookup all the JuiceFactory instances? In Spring there's a getBeansOfType() method which allows for any random hierarchical queries, I'm wondering how to achieve the same with Guice. Reason why I need this is that my modules will be pluggable so I don't know the fruits I'll be handling before hand. Also, I might later want to do a lookup by the HasSeed interface, where I also expect the Apple and Grape instances to be returned, so MultiBinder is not really an option.

Thanks! 

Stephan Classen

unread,
Jun 5, 2018, 6:09:58 PM6/5/18
to google...@googlegroups.com

Multibindings are the way Guice is implementing plug-in mechanism.

The best I can think of is having a single SetBinder and add all pluggable classes there.
Then implement your own methods which iterate over all binded classes and filter for the criteria you need.

class Fruity {

@Inject Set<Object> fruits;

Set<HasSeed> getAllFruitsWithSeed() {
    Set<HasSeed> result = new HashSet<>();
    for (Object candidate : fruits) {
        if (candidate instanceof HasSeed) {
            result.add((HasSeed) candidate);
        }
    }
}

--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-guice...@googlegroups.com.
To post to this group, send email to google...@googlegroups.com.
Visit this group at https://groups.google.com/group/google-guice.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-guice/7e728a22-0d39-44a1-852e-b2dc2a62909a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages