如何获取已安装的 MapBinder 以向其中添加其他绑定

How get already installed MapBinder to add additional bindings into it

我用com.google.inject:guice。在我的项目中,我包含了一个依赖项,它有一个模块(扩展 com.google.inject.AbstractModule 的 class)定义了 MapBinder 这样的

public class ParentGuiceModule extends AbstractModule {    
    @Override
    protected void configure() {
        MapBinder.newMapBinder(binder(), TypeLiteral.get(String.class), TypeLiteral.get(SomeModuleClass.class));
        ...
    }
}

在我的模块 class 中,我想获取 MapBinder 并向其添加新的绑定。我的意思是我想写这样的东西:

public class MyGuiceModule extends AbstractModule {    
    @Override
    protected void configure() {
        MapBinder<String, SomeModuleClass> parentModules = MapBinder.get(binder(), TypeLiteral.get(String.class), TypeLiteral.get(SomeModuleClass.class));
        parentModules.addBinding("MyId").to(MyClass.class);
    }
}    

我该怎么做?我无法更改父模块。

我查看了 MapBinder class,似乎没有任何方法可以安装 MapBinder

这正是 MapBinder 的设计目的——毕竟,如果您从单个模块中知道 MapBinder 中的所有内容,您可以只写 @Provides Map<Foo, Bar>bind(new TypeLiteral<Map<Foo, Bar>>(){})并完成它。

来自MapBinder top-level docs

Contributing mapbindings from different modules is supported. For example, it is okay to have both CandyModule and ChipsModule both create their own MapBinder<String, Snack>, and to each contribute bindings to the snacks map. When that map is injected, it will contain entries from both modules.

不要因为名称 newMapBinder 而气馁:只要您具有与 newMapBinder 完全相同的参数并且将您的两个模块安装在同一个 Injector 中,您就会结束使用一个包含来自两个模块的绑定的映射。