0

如果我有一个接口 IBaseFunction 和这个接口的多个实现。我如何遍历绑定调用每个 ie 上的方法

public class MyModule extends AbstractModule {
  @Override 
  protected void configure() {

bind( IBaseFunction.class).annotatedWith( ExDelete.class).to( ExDeleteFunction.class);
bind( IBaseFunction.class).annotatedWith( ExAdd.class).to( ExAddFunction.class);
...

  }
}

我需要在每个绑定上调用一个函数 'publish() (使处理程序在总线上可用)

我可以像这样单独调用每个绑定上的函数:-

ExDeleteFunction functionExDelete = injector.getInstance( ExDeleteFunction.class);
ExDeleteFunction.publish();
ExAddFunction functionExAdd = injector.getInstance( ExAddFunction.class);
ExAddFunction.publish();

但是我想做的是遍历这些并在所有这些上调用“发布”功能,有没有办法做到这一点?也许使用 injector.getAllBindings() ?像这样的东西:-

  Injector injector = Guice.createInjector( new ServicesModule() );

  Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
  for (Binding<?> binding : bindings.values()) {
      Key<?> key = binding.getKey();
...??

还是有更简单的方法?

4

1 回答 1

2

是的,有一种更简单的方法,称为Multibindings。有了这个,你将能够做类似的事情

public class BaseFunctionsModule extends AbstractModule {
    @Override
    public void configure() {
        Multibinder<BaseFunction> multibinder = Multibinder.newSetBinder(binder(), BaseFunction.class);
        mapBinder.addBinding().to(ExDeleteFunction.class);
        mapBinder.addBinding().to(ExAddFunction.class);
        // others
    }
}

public static void main(String[] args) {
    Injector injector = Guice.createInjector(new BaseFunctionsModule());
    Set<BaseFunction> functions = injector.getInstance(new TypeLiteral<Set<BaseFunction>>() {});
    for (BaseFunction function : functions) {
        function.publish();
    }
}

但是,这样可能无法单独注入你的函数(我不知道,你需要测试一下);您也可以查看MapBinder

于 2013-05-16T18:00:29.107 回答