我有一个输入文件(text => TextFileImporter
或 xml => XmlFileImporter
),其中包含具有不同结构的数据。 Definiton
中描述了一种结构。类(class),所以我的FileImporter
对象保存 Definition
的多个实例.
一个TextFileImporter
应该持有 List<TextDefinition>
和一个 XmlFileImporter
应该持有 List<XmlDefinition>
.
请看一下示例代码:
// Parent classes
abstract class Definition {}
abstract class FileImporter {
protected List<Definition> definitions;
public FileImporter(List<Definition> definitions) {
this.definitions = definitions;
}
public void doSomething() {
// use 'definitions'
}
}
// Text files
class TextDefinition extends Definition {
public void copyLine() {}
}
class TextFileImporter extends FileImporter {
// here should be clear that 'definitions' is of type List<TextDefinition>
// to call 'copyLine()' on its items
}
// XML files
class XmlDefinition extends Definition {
public void copyNode() {}
}
class XmlFileImporter extends FileImporter {
// here should be clear that 'definitions' is of type List<XmlDefinition>
// to call 'copyNode()' on its items
}
正如您根据评论所看到的,我不确定如何更好地处理这个问题。当然,我首先需要构造函数。然后,我不想转换 definitions
的每一项每次调用方法时都指向合适的子类。
我可以在这里合理使用泛型吗?或者还有其他解决方案吗?
最佳答案
你必须引入一些泛型。
// Parent classes
abstract class Definition {}
abstract class FileImporter<T extends Definition> {
protected List<T> definitions;
public FileImporter(List<T> definitions) {
this.definitions = definitions;
}
public void doSomething() {
// use 'definitions'
}
}
// Text files
class TextDefinition extends Definition {
public void copyLine() {}
}
class TextFileImporter extends FileImporter<TextDefinition> {
// here should be clear that 'definitions' is of type List<TextDefinition>
// to call 'copyLine()' on its items
}
// XML files
class XmlDefinition extends Definition {
public void copyNode() {}
}
class XmlFileImporter extends FileImporter<XmlDefinition> {
// here should be clear that 'definitions' is of type List<XmlDefinition>
// to call 'copyNode()' on its items
}
关于java - 覆盖父类的List类型以避免调用方法时进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32328585/