Java根据输入调整数据类型

问题描述

我有多个定义不同对象的类(例如苹果、香蕉、柠檬),以及转换这些对象的多个处理器(例如苹果处理器、香蕉处理器、柠檬处理器)。

我想要一个函数,它有一个对象和一个处理器作为输入,并在给定对象的处理器中启动一个函数。

像这样的事情,显然它不起作用,因为没有为类型 Object 定义 process 函数。

private void doStuff (Object item,Object processor){
    processor.process(item);
}  

除了为每个处理器-项目对编写一个函数之外,还有什么更好的方法可以做到这一点?

解决方法

一种方法是使用泛型

为您的项目(即 Fruit)创建一个超类并使这些项目扩展该类,然后编辑 Processor 类以接受泛型:

doc.LoadHtml("<table><thead><th>Hora</th><th>Estado</th><th>Motivo</th><th>Local</th><th>Recetor</th></thead></table>");

var nodes = doc.DocumentNode.SelectNodes("//thead").ToList();

foreach (var node in nodes) {
  node.Remove();
}

txtResults.Text=doc.Text;

通过这种方式,您只需实例化所需类型的新处理器(即 public class Processor<T extends Fruit>{ public void process(T item){ //do your stuff here,may be check if item is instance of any fruit you need } } )并调用 new Processor<Apple> 方法。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...