简体   繁体   中英

How to auto install all implementations of an interface with guice?

I have the following interface:

public interface IFilterFactory<T extends IFilter> {
    T create(IFilterConfig config);
}

And multiple implementations of it:

public class AndFilter implements IFilter {
    public interface IAndFilterFactory extends IFilterFactory<AndFilter> {}

    // ...
}

public class OrFilter implements IFilter {
    public interface IOrFilterFactory extends IFilterFactory<OrFilter> {}

    // ...
}

in my Guice module, I'm currently installing each module I add this way:

install(new FactoryModuleBuilder().build(IAndFilterFactory.class));
install(new FactoryModuleBuilder().build(IOrFilterFactory.class));

The And and Or filters are just examples but I have many more, some of them requiring specific objects to be injected, thus the factories.

Is there a way with Guice to just say "install all implementations of IFilterFactory " without having to use reflection myself ?

There's nothing for classpath scanning built-in , and despite a lot of existing library options , there's reason to believe that a perfect solution simply can't exist for Java . In any case, enumerating all available classes is known to be slow even in heavily-used libraries, and such a solution would scale with the number of classes in your application, not the number of filters you use.

(To be clear, you're not quite even asking to "install all implementations of IFilterFactory", you're asking "create and install a module with FactoryModuleBuilder for all implementations of IFilterFactory". The factory interface implementation doesn't exist until you generate it with FactoryModuleBuilder.)

You can, however, extract everything aside from the class name itself, so you only have one easy-to-maintain list of classes to bind:

List<Class<?>> filterFactories = ImmutableList.<Class<?>>of(
    IAndFilterFactory.class,
    IOrFilterFactory.class,
    IXorFilterFactory.class,
    HelpIAmTrappedInAFilterFactory.class
);
for (Class<?> clazz : filterFactories) {
  install(new FactoryModuleBuilder().build(clazz));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM