2

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.

Manu
  • 493
  • 6
  • 17

1 Answers1

0

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.

Geno Roupsky
  • 646
  • 5
  • 11
  • Thanks Geno for your solution but I'm trying to avoid the "cast". Is it possible ? because if I use your solution, I need to do an explicit cast : MyChildClass1 myChildClass1 = (MyChildClass1) factoryMap.get("myKey1").create("myParameter"); As i bind a string key to one special implementation in my module, I don't want to precise this implmeentation again. – Manu Nov 28 '11 at 10:51
  • @Manu If your code known the concrete child type, then you don't need the map binder. You can directly inject the specific factory. The MapBinder is usefull if your code only sees `MyParentClass` and doesn't care which concrete implementation will receive. – Geno Roupsky Nov 29 '11 at 16:47