java - 覆盖父类的List类型以避免调用方法时进行强制转换

标签 java generics inheritance

我有一个输入文件(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/

相关文章:

java - 带休息的 Spring 数据 JPA : how to filter out a subset of records in a one-to-many mapping

java - 仅在读取时是否必须使用线程安全的 Map 实现?

java - 如何从数组类型类中获取元素类型类?

java - 内部类中的泛型

c# - 动态命名空间切换

java - 覆盖方法,使参数需要子类

java - 具有不相关返回类型的继承方法

java - 具有数百万个节点的有向图,大多数只有几条边,但少数有数十万个

java - 找不到部署 "war"的子部署 "ear"中命名的持久性单元

c# - 带有 MethodInfo 和泛型类型参数的 Expression.Call