将具体类型的列表强制转换为Java中的接口列表
有没有一种方法可以将具体类型列表转换为Java中的接口列表
例如:
public class Square implements Shape { ... }
public SquareRepository implements Repository {
private List<Square> squares;
@Override
public List<Shape> getShapes() {
return squares; // how can I return this list of shapes properly cast?
}
}
提前感谢,
帽子
# 1 楼答案
如果你真的想这样做,下面的方法可能会奏效
# 2 楼答案
如果您控制
Repository
接口,我建议您重构它以返回List<? extends Shape>
类型的内容这很好:
# 3 楼答案
您可以利用generic wildcards允许将派生列表用作基本列表:
请注意,返回的列表不能添加非空项。(正如Sauer先生指出的,您可以添加
null
,删除也可以。)这是一个折衷方案,不过希望这对你来说无关紧要由于
getShapes()
是一个重写,因此还需要更新Repository
中的返回类型