简体   繁体   English

参数化方法有什么问题?

[英]What's wrong with the parametrized method?

Here is the signature of my method running scheduled tasks:这是我运行计划任务的方法的签名:

private <E extends Enum<E>, T extends Task<E>> void runJob(T task, Map<Enum<E>, 
                                                           Job> taskTypeJobMap, 
                                                           Enum<E> taskType, 
                                                           JpaRepository<T, Long> repository)

Here is the method which runs the previous one:这是运行前一个的方法:

private void runJob(TaskQueue task, Map<TaskType, Job> taskTypeJobMap) {
    runJob(task, taskTypeJobMap, null, taskQueueRepository);
}
   

Here you can see that my classes are parametrized: (TaskType is Enum)在这里你可以看到我的类是参数化的:(TaskType 是 Enum)

public class TaskQueue implements Task<TaskType> { /* ... */ }
public interface Task <T extends Enum<T>> { /* ... */ }
public interface TaskQueueRepository extends JpaRepository<TaskQueue, Long> { /* ... */ }

But my IDE shows an exception:但是我的 IDE 显示异常: 在此处输入图像描述 Where did I make a mistake?我哪里弄错了?

The problem is that you are not passing a Map<Enum<E>,Job> , you are passing a Map<TaskType,Job> .问题是您没有传递Map<Enum<E>,Job> ,而是传递了Map<TaskType,Job> The reason is that generics in Java are not covariant, complicated by the fact that although TaskType is an Enum<TaskType> , and the only possible Enum<TaskType> , an Enum<TaskType> in the Java typesystem is not a TaskType .原因是 Java 中的 generics 不是协变的,尽管TaskTypeEnum<TaskType>并且唯一可能的Enum<TaskType> ,但 Java 类型系统中的Enum<TaskType>不是TaskType这一事实使情况变得复杂。

You need to change the signature of your method to either use:您需要更改方法的签名以使用:

  • Map<TaskType,Job> (accepts only maps with TaskType as key), or Map<TaskType,Job> (仅接受以TaskType作为键的映射),或
  • Map<E,Job>

Similarly, it would probably be better to change the type of the taskType parameter to E as well.同样,最好也将taskType参数的类型更改为E

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM