【发布时间】:2016-05-02 16:32:12
【问题描述】:
我有一个名为 ReportWriter 的接口,它将报告写入 OutputStream,包含 reportRow 列表的 Report 类,也是一个抽象类:
public interface ReportWriter<T extends ReportRow> {
OutputStream writeReport(Report<T> report) throws ReportWriterException;
}
public abstract class Report<T extends ReportRow> {
private List<T> rows = Lists.newArrayList();
...
}
public abstract class ReportRow {...}
现在我有了实现 ReportWriter 的 CsvWriter,
public class CsvWriter<T extends ReportRow> implements ReportWriter {
@Override
public ByteArrayOutputStream writeReport(Report report) throws ReportWriterException {
...
for (T row : report.getRows()) { <-- incompatible type
..write here..
}
}
在上面的代码中,它抱怨不兼容的类型:
require Object found T.
我不明白在 Report 类中我已经指定 T 是 ReportRow 的子类,为什么我会收到这个抱怨?
然后我尝试更新 CsvWriter 的 writeReport 如下:
public class CsvWriter<T extends ReportRow> implements ReportWriter {
@Override
public ByteArrayOutputStream writeReport(Report<T> report) throws ReportWriterException { <--- complain here
...
}
现在它抱怨了:
writeReport(Report<T> report) clashes with writeReport(Report report); both methods have same erasure.
我该如何解决这个问题?谢谢
【问题讨论】:
-
这里的基本问题是您混合了参数化类型和原始类型。您可能应该阅读What is a raw type and why shouldn't we use it?