不兼容的类型 - 使用泛型时找到对象

时间:2013-07-26 13:51:56

标签: java

我遇到以下循环导致错误Incompatible types: Required: Workstation, Found: java.lang.Object的问题。

输入所有内容后,我无法理解为什么它会找到一个Object而不是输入的对象。

private static WorkflowProcess getWorkflowProcessByWorkstationRecursive(Collection<WorkflowProcess> workflowProcesses) {
    for (WorkflowProcess workflowProcess : workflowProcesses) {
        for (Workstation workstation : workflowProcess.getWorkstations()) //ERROR IS HERE

WorkflowProcess.java

abstract public class WorkflowProcess<WorkstationType extends Workstation> {

    private ArrayList<WorkstationType> workstationList = new ArrayList<WorkstationType>();

    public ArrayList<WorkstationType> getWorkstations() {
        return workstationList;
    }

ServerWorkflowProcess.java

abstract public class ServerWorkflowProcess extends WorkflowProcess<ServerWorkstation> {

ServerWorkstation.java

abstract public class ServerWorkstation extends Workstation<ServerWorkflowProcess> {

它有点复杂,但基本上类层次结构如下所示:

SpecificWorkflowProcess延伸TypeOfWorkflowProcess<TypeOfWorkstaton>延伸WorkflowProcess

SpecificWorkstation延伸TypeOfWorkstation<TypeOfWorkflowProcess>延伸Workstation

WorkflowProcessesWorkstation =一对多

2 个答案:

答案 0 :(得分:4)

问题是您使用的是原始类型WorkflowProcess。这意味着您获得的API实际上是普通API的 erasure ,因此getWorkstations的返回类型只变为ArrayList

您可以轻松解决此问题:

private static WorkflowProcess getWorkflowProcessByWorkstationRecursive(
    Collection<WorkflowProcess<?>> workflowProcesses) {
  for (WorkflowProcess<?> workflowProcess : workflowProcesses) {
    ..
  }
}

通过使用通配符,你基本上是在说“我知道这里涉及泛型,但我实际上并不介意集合中WorkstationType类型参数是什么”。

答案 1 :(得分:0)

您必须在第二行中将通用参数添加到workflowProcess的类型:

private static WorkflowProcess getWorkflowProcessByWorkstationRecursive(Collection<WorkflowProcess> workflowProcesses) {
    for (WorkflowProcess<Workstation> workflowProcess : workflowProcesses) {
        for (Workstation workstation : workflowProcess.getWorkstations())