java 实现类转接口_java-如何将一个接口上的实现者转换为另一种接口?

考虑到以下情况,我很难找到一种似乎没有错误的方式来执行此操作

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值