简体   繁体   中英

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)

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: 在此处输入图像描述 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> . 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 .

You need to change the signature of your method to either use:

  • Map<TaskType,Job> (accepts only maps with TaskType as key), or
  • Map<E,Job>

Similarly, it would probably be better to change the type of the taskType parameter to E as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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