考虑到以下情况,我很难找到一种似乎没有错误的方式来执行此操作
public interface IType {}
public interface IMode {}
public interface Factory {
IMode get(T o);
Class getIType();
}
我有上面的接口,并且在类上有一个很大的列表,它们用相应的工厂实现IType和IMode.
我需要能够从一种转换为另一种,
public class A implements IType {}
public class One implements IMode {}
public class AToOne implements Factory {
public IMode get(A o){
return new One();
}
public Class getIType(){
return A.class;
}
}
假设这些类之间存在一对一的映射关系,即对于每个具体的IType,只有一个且只有一个带有相应工厂的具体IMode,我将如何将ITypes列表转换为IModes列表?
即.
private List> factoryList;
public List getConversions(List extends IType> types){
???
}
我的第一次尝试并不顺利,
//Fill this using the getIType() method from each factory
Map, Factory extends IType>> factoryList = new HashMap, Factory extends IType>>();
public List getConversions(List types){
List modes = new ArrayList();
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
is not applicable for the arguments (capture#14-of ? extends IType)
解决方法:
就像我在评论中提到的那样,您只需要使用通用的辅助方法即可访问地图,该方法会执行Factory 到Factory T其中T匹配传入的类型:
Map, Factory extends IType>> factoryList =
new HashMap, Factory extends IType>>();
private IMode convert(T iType) {
//unchecked cast - implementation must guarantee map holds correct data
Factory factory = (Factory)factoryList.get(iType.getClass());
//then convert
return factory.get(iType);
}
您可以从循环中调用此辅助方法:
public List getConversions(List types) {
List modes = new ArrayList(types.size());
for (IType type : types) {
IMode iMode = convert(type);
modes.add(iMode);
}
return modes;
}
标签:generics,java
来源: https://codeday.me/bug/20191201/2079264.html