Google guice - multibinding + generics + assistedinject

有些话、适合烂在心里 提交于 2020-01-04 05:15:23

问题


I have the following classes :

public interface Factory<T extends MyParentClass> {
    public T create(String parameter);
}

public class FactoryImpl1 implements Factory<MyChildClass1> {
    public MyChildClass1 create(String parameter){
    ...
    }
}

public class FactoryImpl2 implements Factory<MyChildClass2> {
    public MyChildClass2 create(String parameter){
    ...
    }
}

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        MapBinder<String, Factory<MyParentClass>> factoryMap = MapBinder.newMapBinder(binder(), new TypeLiteral<String>() {}, new TypeLiteral<Factory<MyParentClass>>(){});
        factoryMap.addBinding("myKey1").to(FactoryImpl1.class);
        factoryMap.addBinding("myKey2").to(FactoryImpl2.class);
    }
}

The syntax in my module is not correct and I don'know how to configure this.

In fact I would like to have a factory for each possible in my factory interface

Thanks in advance for your help.


回答1:


Factory<MyParentClass> is not supertype of Factory<MyChildClass1>, you need to specify a wildcard generic (bound or unbound in this case doesn't matter as you have bound it in the Factory definition).

Try with

MapBinder<String, Factory<?>> factoryMap = MapBinder.newMapBinder(binder(), new TypeLiteral<String>(){}, new TypeLiteral<Factory<?>>(){});

Check here for supertype relationships between generics.



来源:https://stackoverflow.com/questions/8279711/google-guice-multibinding-generics-assistedinject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!