Home > Net >  How do I resolve the unchecked cast problem IntelliJ is highlighting?
How do I resolve the unchecked cast problem IntelliJ is highlighting?

Time:09-28

Context

I’m building a command dispatcher for my CQRS application.

Relevant Code

Command Interface

public interface Command {
  
}

Command Executor Interface

public interface CommandExecutor<T extends Command> {

  Mono<CommandResult> execute(T command);

}

Command Dispatcher

public class CommandDispatcher {

  private final Map<String, CommandExecutor<? extends Command>> executors = new HashMap<>();


  // Example usage
  public static void main(String[] args) {

    CommandDispatcher dispatcher = new CommandDispatcher();

    dispatcher.register(MakeRequestCommand.class.getName(), new MakeRequestCommandExecutor());

    dispatcher
        .dispatch(MakeRequestCommand.class.getSimpleName(), new MakeRequestCommand("Any iPhone"))
        .subscribe(System.out::println);

  }


  public <T extends Command> void register(String commandAlias, CommandExecutor<T> executor) {

    executors.put(commandAlias, executor);

  }


  public <T extends Command> Mono<CommandResult> dispatch(String commandAlias, T command) {

    if (!executors.containsKey(commandAlias)) {

      throw new RuntimeException("No executor registered for command %s".formatted(commandAlias));

    }

    CommandExecutor<T> executor = (CommandExecutor<T>) executors.get(commandAlias);

    return executor.execute(command);

  }

}

The Problem

The following line is producing a warning in IntelliJ.

CommandExecutor<T> executor = (CommandExecutor<T>) executors.get(commandAlias);

Unchecked cast: 'io.freesale.application.command.CommandExecutor<capture<? extends io.freesale.application.command.Command>>' to 'io.freesale.application.command.CommandExecutor'

Is this something I need to be concerned about / is there any way to resolve it (without suppressing warnings

  • Related