java - 如何将一个接口(interface)上的实现者转换为另一个接口(interface)?

标签 java generics

鉴于以下情况,我很难找到一种看起来没有错的方法来做到这一点

public interface IType {}
public interface IMode {}

public interface Factory<T extends IType> {
   IMode get(T o);

   Class<T> getIType();
} 

我有上述接口(interface)和大量的类列表,这些类实现了 ITypeIMode 以及相应的工厂。

我需要能够从一个转换为另一个,例如,

public class A implements IType {}
public class One implements IMode {}

public class AToOne implements Factory<A> {
    public IMode get(A o){
       return new One();
    }

    public Class<A> getIType(){
       return A.class;
    }
}

鉴于这些类存在一对一的映射,即对于每个具体的IType,只有一个具体的IMode对于相应的工厂,我如何将 IType 列表转换为 IMode 列表?

即。

private List<Factory<? extends IType>> factoryList;

public List<IMode> getConversions(List<? extends IType> types){
    ???
}

我的第一次尝试并不顺利,

//Fill this using the getIType() method from each factory
Map<Class<IType>, Factory<? extends IType>> factoryList = new HashMap<Class<IType>, Factory<? extends IType>>();

 public List<IMode> getConversions(List<IType> types){
    List<IMode> modes = new ArrayList<IMode>();

    for(IType type : types){
        //Derp
        Factory<? extends IType> factory = factoryList.get(type.getClass());
        //Error
        factory.get(factory.getIType().cast(type));
    }
}

错误:

 The method get(capture#12-of ? extends IType) in the type
 Factory<capture#12-of ? extends IType>
 is not applicable for the arguments (capture#14-of ? extends IType)

最佳答案

就像我在评论中提到的那样,您只需要使用一个通用的辅助方法来访问 map ,它会从 Factory<? extends IType> 执行未经检查的转换。到 Factory<T>其中 T匹配传入内容的类型:

Map<Class<? extends IType>, Factory<? extends IType>> factoryList =
        new HashMap<Class<? extends IType>, Factory<? extends IType>>();

private <T extends IType> IMode convert(T iType) {
    //unchecked cast - implementation must guarantee map holds correct data
    Factory<T> factory = (Factory<T>)factoryList.get(iType.getClass());
    //then convert
    return factory.get(iType);
}

您可以从循环中调用此辅助方法:

public List<IMode> getConversions(List<IType> types) {
    List<IMode> modes = new ArrayList<IMode>(types.size());
    for (IType type : types) {
        IMode iMode = convert(type);
        modes.add(iMode);
    }
    return modes;
}

关于java - 如何将一个接口(interface)上的实现者转换为另一个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10939956/

相关文章:

java - <T 扩展可识别<?扩展可序列化>>?

java - 如何识别被取消的 ScheduledFuture 是否真的没有被取消?

java - 如何在java中添加超过3个面板的GUI

java泛型加法

c# - 使用最小起订量模拟具有泛型参数的类型

java - 如果泛型支持子类型,哪种类型安全会丢失?

java - 将通用对象与整数进行比较

java - 如何将 InputStream 转换为 int

java - 如何使用 OpenCV 检测文本

java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java :255) Error