2

私は次のクラスを持っています:

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);
    }
}

モジュールの構文が正しくなく、構成方法がわかりません。

実際、工場のインターフェースで可能なものごとに工場を持ちたいと思っています

よろしくお願いします。

4

1 に答える 1

1

Factory<MyParentClass>のスーパータイプではないFactory<MyChildClass1>場合、ワイルドカード ジェネリックを指定する必要があります (ファクトリ定義でバインドしているため、この場合、バインドされているかどうかは問題ではありません)。

試してみてください

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

ジェネリック間のスーパータイプの関係については、こちらを確認してください。

于 2011-11-26T23:23:30.730 に答える