如何从他们的类中获取Guice的对象列表?

时间:2014-05-13 04:08:32

标签: java guice

我定义了一些"变形金刚" (功能)并需要它们的列表。它们中的每一个都是由Guice创建的,我使用此代码获取列表:

public class CombinedTransformer extends AbstractTransformer {
    @Inject CombinedTransformer(
            FirstTransformer firstTransformer,
            SecondTransformer secondTransformer,
            ThirdTransformer thirdTransformer) {
        transformers = ImmutableList.of(
                firstTransformer,
                secondTransformer,
                thirdTransformer);

我的清单很长,所以我想知道是否有更简单的方法,比如

public class CombinedTransformer extends AbstractTransformer {
    @Inject CombinedTransformer(Injector injector) {
        transformers = injector.getList(
            FirstTransformer.class,
            SecondTransformer.class,
            ThirdTransformer.class);
    }
}

有类似的东西吗?

1 个答案:

答案 0 :(得分:1)

您可以使用multibindings

Multibinder<AbstractTransformer> multibinder = Multibinder.newSetBinder(binder(), AbstractTransformer.class);
multibinder.addBinding().to(FirstTransformer.class);
multibinder.addBinding().to(SecondTransformer.class);
multibinder.addBinding().to(ThirdsTransformer.class);

然后你可以注入Set<AbstractTransformer>

@Inject
CombinedTransformer(Set<AbstractTransformer> transformers) {
    // do whatever you want with the set
}

但如果不直接使用多重绑定,就无法做到。如果你真的需要使用静态已知的类列表来获取对象列表,可以在注入器周围编写一个包装器并使用它:

public class ListInjectorWrapper {
    private final Injector injector;

    @Inject
    ListInjectorWrapper(Injector injector) {
        this.injector = injector;
    }

    @SafeVarargs
    public final <T> List<T> getList(Class<? extends T>... classes) {
        return Arrays.stream(classes).map(clazz -> injector.getInstance(clazz))
            .collect(Collectors.toList());
    }
}

然后注入并使用它来获取变形金刚:

@Inject
CombinedTransformer(ListInjectorWrapper injectorWrapper) {
    transformers = injectorWrapper.getList(
        FirstTransformer.class,
        SecondTransformer.class,
        ThirdTransformer.class
    );
}