Google guice - 多重绑定+泛型+辅助对象 [英] Google guice - multibinding + generics + assistedinject

查看:274
本文介绍了Google guice - 多重绑定+泛型+辅助对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

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

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

public class FactoryImpl2实现Factory< MyChildClass2> {
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)。(FactoryImpl1.class);
factoryMap.addBinding(myKey2)。(FactoryImpl2.class);


我的模块中的语法不正确, '知道如何配置这个。



事实上,我想为我的工厂界面中的每个可能的工厂都有一个工厂。




解决方案

工厂< MyParentClass> 不是超类型的 Factory< MyChildClass1> ,您需要指定通配符泛型(在这种情况下绑定或非绑定并不重要,因为您已将它绑定到Factory

试一下

  MapBinder< String,Factory< ?>> (),new TypeLiteral< String> 

检查这里为泛型之间的超类型关系。


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.

解决方案

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.

这篇关于Google guice - 多重绑定+泛型+辅助对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆