Google guice - multibinding + generics + assistedi

2019-07-22 09:03发布

问题:

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.